Showing posts with label Callback. Show all posts
Showing posts with label Callback. Show all posts

Wednesday, January 19, 2011

Stock Market Ticker For Website

In this article we shall work out on Live stock market ticker for website. To develop live stock market ticker for website the basic requirement is to have live data. Free live data is available at some cost, but to display tickers on website we can always go for two to three minutes delayed data, which we can download from Yahoo Finance. Yahoo Finance is giving enable use to download CSV file in the manner we want. Once we get the CSV file logic which remains is to display data and Polling of data at certain interval

Check out folder structure of our Demo Code

(Note: Demo contains Cross Currency Data as well; which will be same as Stock market data.)

In this article we shall be considering major stock exchanges, and in demo code we shall see updates related to stock exchanges.
  • DOW (Symbol: ^DJI)
  • Nasdaq (Symbol: ^IXIC)
  • S&P 500 (Symbol: ^GSPC)
  • FTSE 100 (Symbol: ^FTSE)
  • DAX (Symbol: ^GDAXI)
  • CAC 40 (Symbol: ^FCHI)
  • Hang Seng (Symbol: ^HSI)
  • NIKKEI 225 (Symbol: ^N225)
  • Straits Times (Symbol: ^STI)
  • BSE India (Symbol: ^BSESN)
  • NSE India (Symbol: ^NSEI)

If you go to Yahoo Finance and put any of the Symbol you can check all related data. Also that data is allowed to download, we are going to use this downloaded data to display live (little delayed) data to develop Stock Market Ticker for Website. (Note: If you are not aware about ICALLBack Event handler, please refer this article ---> ICallback Event Handler Article
We are going to get data from Yahoo Finance in CSV format. So we shall write logic accordingly. Following is the function to convert CSV in to Data Table.

public static DataTable csvToDataTable(string strData, bool isRowOneHeader)
    {
        DataTable csvDataTable = new DataTable();
        //no try/catch - add these in yourselfs or let exception happen
        String[] csvData = strData.Replace("\r", "").Replace("=X", "").Split('\n');
        //if no data in file ‘manually’ throw an exception
        if (csvData.Length == 0)
        {
            throw new Exception("CSV File Appears to be Empty");
        }

        String[] headings = csvData[0].Split(',');
        int index = 0; //will be zero or one depending on isRowOneHeader
        if (isRowOneHeader) //if first record lists headers
        {
            index = 1; //so we won’t take headings as data
            //for each heading
            for (int i = 0; i < headings.Length; i++)
            {
                //replace spaces with underscores for column names
                headings[i] = headings[i].Replace("", "_");
                //add a column for each heading
                csvDataTable.Columns.Add(headings[i], typeof(string));
            }
        }
        else //if no headers just go for col1, col2 etc.
        {
            for (int i = 0; i < headings.Length; i++)
            {
                //create arbitary column names
                csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof(string));
            }
        }
        //populate the DataTable
        for (int i = index; i < csvData.Length - 1; i++)
        {
            //create new rows
            DataRow row = csvDataTable.NewRow();
            for (int j = 0; j < headings.Length; j++)
            {
                //fill them
                row[j] = csvData[i].Split(',')[j];
            }
            //add rows to over DataTable
            csvDataTable.Rows.Add(row);
        }

        //return the CSV DataTable
        return csvDataTable;
    }

Another Important Function for our development of Stock Market Ticker for website is, the function which will call Yahoo Finance to fetch desired data.

We shall user WebRequest Class to call remove CSV file i.e. Read a downloadable CSV file from remote server. Check out following function.

 public DataTable CallYahooFinance()
    {
        WebRequest req = WebRequest.Create(StaticVariables.Markets);
        WebResponse result = req.GetResponse();
        Stream ReceiveStream = result.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader sr = new StreamReader(ReceiveStream, encode);
        string output = string.Empty;
        Char[] read = new Char[256];
        int count = sr.Read(read, 0, read.Length);
        while (count > 0)
        {
            String str = new String(read, 0, count);
            output += str;
            count = sr.Read(read, 0, read.Length);
        }
        output = output.Replace("^DJI", "DOW").Replace("^IXIC", "NASDAQ").Replace("^GSPC", "S&P500");
        output = output.Replace("^FTSE", "FTSE 100").Replace("^GDAXI", "DAX").Replace("^FCHI", "CAC 40");
        output = output.Replace("^HSI", "HANG SENG").Replace("^N225", "NIKKEI 225").Replace("^STI", "STRAITS TIMES");
        output = output.Replace("^BSESN", "SENSEX").Replace("^NSEI", "NIFTY");
        DataTable DT = csvToDataTable(output, false);
        DT.Columns[0].ColumnName = "Market";
        DT.Columns[1].ColumnName = "Last Trade";
        DT.Columns[2].ColumnName = "Change (in %)";
        return DT;
    } 

In above code "output" is the string i.e. CSV string and we have replaced Yahoo Finance Symbols with the Name of the Stock Index.

If you check above function Webrequest.Create Method contains URL. To get CSV File we are using following URL, if you simple copy paste the URL you can download CSV file. URL for Stock Market Ticker is set into Static variable.

public static class StaticVariables
{
public static string Markets = "http://download.finance.yahoo.com/d/quotes.csv?s=%5EDJI,%5EIXIC,%5EGSPC,%5EFTSE,%5EGDAXI,%5EFCHI,%5EN225,%5EHSI,%5ESTI,%5EBSESN,%5ENSEI&f=sl1c1&e=.csv";
}

Thats it now we got the relevant data from yahoo finance which we can display the way we want. We are using ICallback Event handler to poll data from Yahoo Server. Now if you are aware about ICallback Simply check out following functions. Where we are not doing anything special.


protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            String cbReference =
                Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
            String callbackScript;
            callbackScript = "function CallServer(arg, context)" +
                "{ " + cbReference + ";}";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
        }
    }

Also check Region for ICallback Implementation
public void RaiseCallbackEvent(String eventArgument)
    {
    
    }
    public String GetCallbackResult()
    {
        GridView GridView1 = new GridView();
        GridView1.DataSource = CallYahooFinance();
        GridView1.DataBind();

        return getHTML(GridView1);
    }


public string getHTML(GridView _grid)
    {
        string result = string.Empty;
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            _grid.RenderControl(htw);
            htw.Flush();
             result = sw.ToString();
        }
        return result;
    }
//getHTML returns HTMLString for GRIDView

Now in the HTML of our page we have only following tags.

We use following JavaScript to Fetch live data from server side at the interval of 1000mili second.

function call()
    {
    window.document.getElementById('_polling').style.display="";
    CallServer("", "");
    }
    
     function ReceiveServerData(retValue)
    {   
        document.getElementById("result").innerHTML = retValue;
        window.document.getElementById('_polling').style.display="none";
        setTimeout("call()",1000); //Set polling to 1000mili second
    }

Implementation of above code is very simple check out Demo code for the same.
Download Demo Code here --> Stock Market Ticker For Website.zip Submit this story to DotNetKicks

Read more...

Friday, August 13, 2010

Page Methods

This article is all about the page methods and their usage. PageMethods is the part of Ajax.net and Script Manager.
MS Ajax gives us ability to directly create a web method on aspx page. And also enable to directly call this web method from the page. This method is termed as Page Method.
This is very easy way to implement Ajax functionality on the page. Like ICallback event handler here also we need to manipulate the string.
Page Method works simply as Web Methods
Script Manager Play critical role for the use of Page Methods, we need to set EnablePageMethods attribute to true.

To use web method attribute in Aspx page, use namespace
using System.Web.Services
Page Method should be static, as per the design by MS. So our web method (Page Method) will be as follows.

Now to call above method from client script we need to add PageMethods before the method name
PageMethods.HelloUser("Test User");
This will simply call the Method defied in Page, i.e. .cs file
Many times we need to handle different methods in different way, so in that case we need some special mechanism to handle the response from the server. We may also need to handle method failure errors in some customized way; we can also achieve this by adding extra parameters in PageMethods call.
In short we can add callback methods for successful invocation of pagemethods as well as for the failure of the pagemethod.

Basic Method prototype is
PageMethods.MethodName([para1,para2,…],[OnSucceeded, defaultFailedCallback,userContext]);

Above code work perfectly for normal scenario.
There might be possibility that we create our own JavaScript wrapper class, which internally uses PageMethods in that’s case, we might have following requirements.
  • Set defaultFailedCallback
  • Set defaultSucceededCallback
  • get defaultFailedCallback
  • get defaultSucceededCallback
  • set timeout
  • get timeout
Let’s say we have defined default Failed and Succeeded callbacks. Thus whenever we call some method like PageMethod.HelloUser(username), now if this method call completes its execution successfully our default Succeeded callback function will be called automatically. If method throws some error or failed, default Failed callback function will be called.
Also we need to call some already existing PageMethods but from some other pages; then in that case we should be able to set the path of the page in which methods are defined.
Considering above requirement we can modify the code as below.

With this understanding we can use pageMethods very effectively to handle static Page methods.

Download Demo Code here --> PageMethod3.5.zip

Submit this story to DotNetKicks

Read more...