Tuesday, September 6, 2011

ASP.Net parsing Google API using XML

Perhaps you are wanting to put a stock ticker or weather appliance on your website using Google’s APIs.  With a few lines of code we can accomplish this and read the XML returned from Google within a stream so that we do not need to write anything to the server.  There are several reasons we would not want to write to the server, first and foremost being security.  Giving any application write rights to the file directory is dangerous.  There are very few reasons why you would want to enable writing to the server.  Secondly, and in our particular instance, this does nothing but slow processing down.  Why waste the time writing to the file structure only to read the file back into memory?  Let’s just deal with it in memory.

In this instance, we are going to read the Dow Jones Industrial Average from the Google API.  At the end of the article, I am certain that you are going to think to yourself – Wow, that was easy. 
So as a setup, the Google API accepts .DJI as the stock symbol for DJIA (Google also accepts t for AT&T and f for Ford).

So we need to create either a Class Library with a class file and import that into our application or in our application we need to create a class.
As with best practices, we’ll create a Class Library and then import it into our application:
So you should have VS2010 open with a new web application (or one where you want to post stocks), go ahead and open vs2010 again (second instance).   Click File | New Project.
You will now want to Create a Class Library.  Name it googleLibrary but pay attention to the directory where you save your solution as you will need it to import into your application.
When you have all your settings set appropriately, Go ahead and click Ok and it will open your new project.
Right Click Class1 in your solution explorer and Delete it.
Right Click your solution and then Left Click Add New.  Select Class and name it googleStockAPI (Just for clarification).

This is where things start to get interesting.  We are going to need some properties and supporting parameters to help our class, one of which is a StringBuilder.
To gain access to our StringBuilder, we need to import the namespace System.Text, so in your declarative section:
Imports System.Text
Now we need to declare and instanciate some private variables that will be used to house data:
    Private Property high As String = ""
    Private Property low As String = ""
    Private Property last As String = ""
    Private Property change As String = ""
    Private Property company As String = ""
We need some public variables so that we can use them outside the class (and in our web application):
    Public Property symbol As String = ""
    Public Property ticker As String = ""
Finally, we need a stringbuilder to create our HTML to display the ticker:
Private tickbuilder As StringBuilder = New StringBuilder
This concludes the various variables that we need in order to house our stock ticker data.  Now we need to create a method in order to get the google XML on our particular stock.  We need to create a Sub (as we are not returning data, it is all being returned through the ticker property).
Public Sub getSymbolQuotes()
        Dim doc As XDocument = XDocument.Load("http://www.google.com/ig/api?stock=" & symbol)
        company = doc.Root.Descendants("finance").Descendants("company").First().FirstAttribute().Value.ToString()
        change = "$" & doc.Root.Descendants("finance").Descendants("change").First().FirstAttribute().Value.ToString()
        last = "$" & doc.Root.Descendants("finance").Descendants("last").First().FirstAttribute().Value.ToString()
        low = "$" & doc.Root.Descendants("finance").Descendants("low").First().FirstAttribute().Value.ToString()
        high = "$" & doc.Root.Descendants("finance").Descendants("high").First().FirstAttribute().Value.ToString()
        buildTicker()
        
        ticker = tickbuilder.ToString
    End Sub
What in the world are we doing here?
Well first we are declaring an XDocument (XML Document) and then setting that to the return we get from the Google Stock API (which is XML Formatted).  The document we are requesting from Google is dependent on the value of the symbol parameter (We’ll look at how to set this once we get to our web application).  From there, we are simply parsing out the particular values we are looking for each parameter of the class.
Each value is being populated from the Root node and then finds the descendants (children) of that node until we find our attribute.
Now that we have populated our parameters, we need to form HTML so that we can display it to our users.  This is where the buildTicker method comes in.  Once again we are not returning a value (it is all being handled by properties) to our calling method, so we’ll use a Sub here:
    Public Sub buildTicker()
        If (Not company = ""Then
 
            tickbuilder.Append(company)
            tickbuilder.Append("<br />")
            If Not (high = "$"Then
                tickbuilder.Append(" High: " & high)
            Else
                tickbuilder.Append(" High: $0.00")
            End If
            If Not (low = "$"Then
                tickbuilder.Append(" Low: " & low)
            Else
                tickbuilder.Append(" Low: $0.00")
            End If
            If Not (last = "$"Then
                tickbuilder.Append(" Last: " & last)
            Else
                tickbuilder.Append(" Last: $0.00")
            End If
            If Not (change = "$"Then
                tickbuilder.Append(" Change: " & change)
            Else
                tickbuilder.Append(" Change: $0.00")
            End If
            tickbuilder.AppendLine()
        Else
            tickbuilder.Append("Unknown Symbol")
        End If
    End Sub
Basically, we are ensuring that everything has a value (If you try to pull the data before 9:30 or after 16:30 the market is closed and you will receive NULLs, so we’d rather display $0.00 rather than $).  Also we are ensuring we have a valid stock ticker otherwise we display “Unknown Symbol” to the user.
So we use our StringBuilder tickBuilder and populate it with the values returned from Google in HTML format.  The company will be on a line by itself and the rest of the ticker information will display under it.
This in turn will populate our public property ticker (which we can then call from our web application).
This concludes our class library portion of the application.  So Right Click your solution and select build, unless you have changed the properties, this will build into your debug directory of your solution.

In your web application, you will want to add a Literal control where you want your stock information to display:
<asp:Literal ID="litGoogleStocks" runat="server" Text="&nbsp;"></asp:Literal>
We have gone ahead and made it equal a space “ “ so that the literal will occupy real estate on the webform even though we have not looked up any stocks.
Now we have to import your reference (to the class you built).  So Right Click you solution.  Then click Add Reference.  Click the Browse Tab.  Move to the directory structure of where you saved your class library and in your Bin/Debug directory you will find your .dll (should be googleLibrary.dll).
Now that we have the reference, we need to import the namespace so that we can use the class.  In your page code-behind add:
Imports googleLibrary
Now that we have the Library available to use, we need to declare the class and instantiate it.
So in our Page.Load method, we need to add the following code:
Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgsHandles Me.Load
Dim indicies As googleStockAPI = New googleStockAPI
            Dim stocks As String = ""
            indicies.symbol = ".DJI"
            indicies.getSymbolQuotes()
            litGoogleStocks.Text = indicies.ticker & "<br />"
End Sub
Here we are instantiating our class and then populating the symbol property.  Then we are calling our method to get the XML from Google and finally populating our literal from our returned text from the stringbuilder.
We should now see our stock ticker.
If we want to load more stocks we simply reassign the class variable to a new instance:
indicies = New Ticker
            indicies.symbol = ".INX"
            indicies.getSymbolQuotes()
… More code …
The weather and other APIs from Google have a lot of the same functionality.  So now we can use Google Data and format it how we want so that it fits our application and is pretty transparent to the user.

Happy .Netting… Saleh

No comments:

Post a Comment