Source Viewer: MyWebClient.cs
Font Size:
1
2
3
4
5
6
7
MorphArray.cs
Morpho.cs
MyWebClient.cs
PronounceWord.cs
syslog.cs
SyslogTraceListener.cs
MQ
..
// MyWebClient.cs // ------------------------------------------------------------------ // // WebClient is a handy class in the .NET Fx, but not present in the .NET CF. // This is my poor-man's implementation, to allow easy download of pages and bytestreams // from HTTP, in the .NET CF. It builds on HttpWebRequest. // // Author: Dinoch // built on host: DINOCH-2 // Created Thu Apr 23 09:16:38 2009 // // last saved: // Time-stamp: <2009-June-10 21:43:23> // ------------------------------------------------------------------ // // Copyright (c) 2009 by Dino Chiesa // All rights reserved! // // ------------------------------------------------------------------ using System; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Runtime.InteropServices; namespace Ionic.WebTests { public class MyWebClient { public string DownloadString(string uri) { string result= null; HttpWebResponse response= null; try { HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(uri); response= (HttpWebResponse) request.GetResponse(); Encoding responseEncoding = Encoding.GetEncoding(response.CharacterSet); using (StreamReader sr = new StreamReader(response.GetResponseStream(), responseEncoding)) { result = sr.ReadToEnd(); } } finally { if (response!= null) response.Close(); } return result; } public byte[] DownloadData(string uri) { byte[] result= null; HttpWebResponse response= null; try { HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(uri); response= (HttpWebResponse) request.GetResponse(); using (System.IO.Stream stream= response.GetResponseStream()) { result = stream.ReadAllBytes(); } } finally { if (response!= null) response.Close(); } return result; } } public static class Extensions { ///
/// Reads the contents of the stream into a byte array. /// data is returned as a byte array. An IOException is /// thrown if any of the underlying IO calls fail. ///
///
The stream to read. ///
A byte array containing the contents of the stream.
///
The stream does not support reading.
///
Methods were called after the stream was closed.
///
An I/O error occurs.
public static byte[] ReadAllBytes(this System.IO.Stream source) { long originalPosition = 0; if (source.CanSeek) { originalPosition= source.Position; source.Position = 0; } try { byte[] readBuffer = new byte[4096]; int totalBytesRead = 0; int bytesRead; while ((bytesRead = source.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0) { totalBytesRead += bytesRead; if (totalBytesRead == readBuffer.Length) { int nextByte = source.ReadByte(); if (nextByte != -1) { byte[] temp = new byte[readBuffer.Length * 2]; Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length); Buffer.SetByte(temp, totalBytesRead, (byte)nextByte); readBuffer = temp; totalBytesRead++; } } } byte[] buffer = readBuffer; if (readBuffer.Length != totalBytesRead) { buffer = new byte[totalBytesRead]; Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead); } return buffer; } finally { if (source.CanSeek) source.Position = originalPosition; } } } public class MyWebClientTest { // ctor public MyWebClientTest () {} string _wordToPronounce; // ctor public MyWebClientTest (string[] args) { for (int i=0; i < args.Length; i++) { switch (args[i]) { case "-?": throw new ArgumentException(args[i]); default: if (_wordToPronounce != null) throw new ArgumentException(args[i]); _wordToPronounce = args[i]; break; } } // default value if (_wordToPronounce == null) _wordToPronounce = "earnest"; } private static string MwDictionaryUriTemplate= "http://www.merriam-webster.com/dictionary/"; private string GetMwDictionaryPageMarkup(string word) { string uriToGet = MwDictionaryUriTemplate + word; return GetPageMarkup(uriToGet); } private string GetPageMarkup(string uri) { string pageData = null; MyWebClient client = new MyWebClient(); pageData = client.DownloadString(uri); return pageData; } private string GetPronunciationPageUri(string dictionaryPageMarkup) { var re0 = new Regex("popWin\\('([^']+)'\\)"); string result= null; if (re0.IsMatch(dictionaryPageMarkup)) { Match m = re0.Match(dictionaryPageMarkup); result = String.Format("http://www.merriam-webster.com/{0}", m.Groups[1].ToString()); } return result; } private string GetWavUri(string pronunciationPageMarkup) { var re0 = new Regex("
"); } public static void Main(string[] args) { try { MyWebClientTest me = new MyWebClientTest(args); me.Run(); } catch (System.Exception exc1) { Console.WriteLine("Exception: {0}", exc1.ToString()); Usage(); } } } public class WavPlayer { // from http://www.codeguru.com/Csharp/Csharp/cs_graphics/sound/article.php/c6143/ ? // and http://www.eggheadcafe.com/articles/20030302.asp // For some reason, the 2nd param, hModule, must be of type IntPtr if I am // playing a byte[], and it must be of type long if I am playing a wav // file specified via a string. ?? Ah, the mysteries of P/Invoke. //[DllImport("WinMM.dll", EntryPoint="PlaySound")] //public static extern bool PlaySoundBytes(byte[] wavData, long hModule, UInt32 flags); //[DllImport("Winmm.dll")] [DllImport("WinMM.dll", EntryPoint="PlaySound")] public static extern bool PlaySoundBytes(byte[] data, IntPtr hMod, UInt32 dwFlags); //[System.Runtime.InteropServices.DllImport("WinMM.dll", EntryPoint="PlaySoundW" )] [System.Runtime.InteropServices.DllImport("WinMM.dll", EntryPoint="PlaySound")] public static extern bool PlaySoundFile( string filename, long hModule, UInt32 flags ); // this will not work! [System.Runtime.InteropServices.DllImport("WinMM.dll", EntryPoint="PlaySound")] public static extern bool PlaySoundFile( string filename, IntPtr hModule, UInt32 flags ); // flag values for SoundFlags argument on PlaySound public static uint SND_SYNC = 0x0000; // play synchronously (default) public static uint SND_ASYNC = 0x0001; // play asynchronously public static uint SND_NODEFAULT = 0x0002; // silence (!default) if sound not found public static uint SND_MEMORY = 0x0004; // pszSound points to a memory file public static uint SND_LOOP = 0x0008; // loop the sound until next sndPlaySound public static uint SND_NOSTOP = 0x0010; // don't stop any currently playing sound public static uint SND_NOWAIT = 0x00002000; // don't wait if the driver is busy public static uint SND_ALIAS = 0x00010000; // name is a Registry alias public static uint SND_ALIAS_ID = 0x00110000; // alias is a predefined ID public static uint SND_FILENAME = 0x00020000; // name is file name public static uint SND_RESOURCE = 0x00040004; // name is resource name or atom public static uint SND_PURGE = 0x0040; // purge non-static events for task public static uint SND_APPLICATION = 0x0080; // look for application-specific association public static void Play1(string wavFilename, uint flags) { // byte[] bname = System.Text.Encoding.ASCII.GetBytes(wavFilename); // PlaySound(bname,flags); //System.IntPtr NULL = (System.IntPtr) 0; //PlaySound(wavFilename, System.IntPtr.Zero, flags | WavPlayer.SND_FILENAME); PlaySoundFile(wavFilename, 0, flags | WavPlayer.SND_FILENAME); } public static void Play3(string wavFilename, uint flags) { // byte[] bname = System.Text.Encoding.ASCII.GetBytes(wavFilename); // PlaySound(bname,flags); //System.IntPtr NULL = (System.IntPtr) 0; //PlaySound(wavFilename, System.IntPtr.Zero, flags | WavPlayer.SND_FILENAME); PlaySoundFile(wavFilename, IntPtr.Zero, flags | WavPlayer.SND_FILENAME); } public static void Play2(string wavFilename, uint flags) { byte[] bytes = System.IO.File.ReadAllBytes(wavFilename); Console.WriteLine("bytes= array({0})", bytes.Length); PlaySoundBytes(bytes, IntPtr.Zero, flags | SND_MEMORY); //PlaySound(bytes, IntPtr.Zero, SND_ASYNC | SND_MEMORY); } public static void Play(byte[] wavData, uint flags) { PlaySoundBytes(wavData, IntPtr.Zero, flags | SND_MEMORY); } public static void PlayUri(string uri, uint flags) { using (WebClient client = new WebClient ()) { // Add a user agent header in case the requested URI contains a query. // client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); using (System.IO.Stream s = client.OpenRead(uri)) { byte[] bytes = s.ReadAllBytes(); PlaySoundBytes(bytes, IntPtr.Zero, flags); } } } public static void StopPlay() { PlaySoundBytes(null, IntPtr.Zero, SND_PURGE); } public static void PlayWavResource(string wav) { // get the namespace string strNameSpace= System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString(); // get the resource into a stream System.IO.Stream str = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream( strNameSpace +"."+ wav ); if ( str == null ) return; // bring stream into a byte array byte[] bStr = new Byte[str.Length]; str.Read(bStr, 0, (int)str.Length); // play the resource PlaySoundBytes(bStr, IntPtr.Zero, SND_ASYNC | SND_MEMORY); } } }
The srcview page has been enjoyed 291584 times since 18 September 2003