Build a C# Stock Quote WebService Part 1/2 - Building the Ticker (Page 2 of 4 )
If you don't have the full .NET Beta 1 Visual Sudio release, that's OK - you can build this stuff in Notepad and compile and run it just fine, as long as you've downloaded and installed the .NET Framework SDK.
I prefer the Visual Studio IDE for the Intellisense and all the cool access to servers, services, databases, and even Webservices (wherever in the world they may reside) which all get "wired up live" right into your IDE and can be brought in to one central location at your fingertips. But sometimes it's nice to just whip out NotePad or EditPlus and start codin' (kind of like when your Commodore 64 used to come up with the blue screen saying "38632 BASIC BYTES FREE"-- man those were the days...).
First we need to start a new .asmx file because that's what tells the CLR (Common Language Runtime) that this is a Webservice. We start out by declaring our PageLanguage and starting class name, along with the CLR references that we'll need for the webservice: <%@ WebService Language="C#" class="StockQuote" %> using System; using System.Web.Services ; using System.Net; using System.IO; using System.Text;
Next we declare our public class "StockQuote" as a webservice, with the [WebMethod] directive: public class StockQuote : WebService { [WebMethod]
Then we declare our public function and set up some required variables, along with the beginning of our try-catch block: public string GetQuote(string symbol) { string result = null; try { //URL to Yahoo spreadsheet format stock quote server... string serverURL = @"http://quote.yahoo.com/d/quotes.csv?s="+symbol+"&f=sl1d1t1c1ohgvj1pp2owern&e=.csv"; char[] delim = {' '}; char[] delim2 = {','}; string[] symbols = symbol.Split(delim); string sTemp = @""; string sContentTemp = @""; string sContentNew = @""; string strChar = "";
We then create a HttpWebRequest object for the stock URL: HttpWebRequest webreq = (HttpWebRequest)WebRequestFactory.Create(serverURL);
-- and Retrieve HttpWebResponse object from the stock URL using the StreamReader object: HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse(); StreamReader strm = new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);