This is a migrated thread and some comments may be shown as answers.

Updating Grid with a WebService

2 Answers 85 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Tracy Cole
Top achievements
Rank 1
Tracy Cole asked on 28 Jul 2009, 07:34 PM
I'm working with a Grid based on the online demo using the Stock Quote WebService.    I want to be able to use the name of the stock and/or index instead of the symbol.     I've changed the yahooFeedTemplate URL to return the name, but the code breaks whenever a name contains a comma.   Has anyone worked with the StockQuoteService and modified it to handle names with commas?   Also, would it be possible to return an additional field to my grid based on an evaluation of the change in price.   For example, if the change percentage is positive return GridImage.ImageUrl = "Images/Up.gif" or GridImage.Image.Url = "Images/Down.gif" if it is negative.    The code in the StockQuoteService is little more complex than I'm used to working with, so thanks in advance for any assistance.  Note, in the code below I'm still referring to StockTicker but the first item returned from the Yahoo feed is actually the name.

 
Imports System  
Imports System.Collections.Generic  
Imports System.ComponentModel  
Imports System.Data  
Imports System.IO  
Imports System.Net  
Imports System.Text  
Imports System.Web  
Imports System.Web.Services  
Imports System.Xml  
Imports System.Globalization  
 
 
<WebService([Namespace]:="http://www.telerik.com/"), WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _  
Public Class StockQuoteService  
    Inherits WebService  
    Private random As Random  
    Private yahooFeedTemplate As String = "http://finance.yahoo.com/d/quotes.csv?s={0}&f=nl1d1t1c1ohgv&e=.csv" 
 
    Public Sub New()  
        random = New Random(DateTime.Now.Millisecond)  
    End Sub 
 
    Property SessionQuotesData() As String 
        Get 
            Return HttpContext.Current.Session("TelerikAspAjaxGridApplication")  
        End Get 
        Set(ByVal value As String)  
            HttpContext.Current.Session("TelerikAspAjaxGridApplication") = value  
        End Set 
    End Property 
 
    <WebMethod(), Description("Gets stock quote for a specific symbol")> _  
    Public Function GetStockQuotes(ByVal stockTickers As StringAs DataSet  
        Dim stockTickerList As String() = stockTickers.Split(","c)  
        Dim index As Integer 
        For index = 0 To stockTickerList.Length - 1  
            stockTickerList(index) = stockTickerList(index).Trim()  
        Next index  
 
        Dim quotes As List(Of Quote) = New List(Of Quote)  
        
            Dim url As String = String.Empty  
            Dim webRequest As WebRequest = Nothing 
            Dim webResponse As WebResponse = Nothing 
            Dim stockTicker As String 
            For Each stockTicker In stockTickerList  
                url = String.Format(yahooFeedTemplate, HttpUtility.UrlEncode(stockTicker))  
                webRequest = HttpWebRequest.Create(url)  
                webResponse = webRequest.GetResponse()  
 
                Dim quote As Quote = GetQuoteData(webResponse.GetResponseStream())  
                quotes.Add(quote)  
            Next stockTicker  
 
 
        SerializeQuotesData(quotes)  
 
        Dim dataset As New DataSet("QuotesDataSet")  
        Dim data As XmlReader = XmlReader.Create(New System.IO.StringReader(SessionQuotesData))  
        dataset.ReadXml(data)  
        Return dataset  
    End Function 
 
    
 
 
    Private Overloads Function GetQuote(ByVal bufferList() As StringAs Quote  
        Dim stockTicker As String = bufferList(0)  
        Dim stockQuote As [Decimal] = [Decimal].Parse(bufferList(1), CultureInfo.InvariantCulture)  
        Dim lastUpdated As DateTime = DateTime.Parse((bufferList(2) + " " + bufferList(3)), CultureInfo.InvariantCulture)  
        Dim change As [Decimal] = [Decimal].Parse(bufferList(4), CultureInfo.InvariantCulture)  
        Dim dailyMaxRange As [Decimal] = 0D  
        If (bufferList(6) <> "N/A"Then 
            dailyMaxRange = [Decimal].Parse(bufferList(6), CultureInfo.InvariantCulture)  
        End If 
 
        Dim dailyMinRange As [Decimal] = 0D  
        If (bufferList(7) <> "N/A"Then 
            dailyMinRange = [Decimal].Parse(bufferList(7), CultureInfo.InvariantCulture)  
        End If 
 
        Return New Quote(stockTicker, stockQuote, lastUpdated, change, dailyMinRange, dailyMaxRange)  
    End Function 
 
 
    Private Overloads Function GetQuote(ByVal quoteNode As XmlNode) As Quote  
 
        Dim stockTicker As String = quoteNode.Attributes("stockTicker").Value  
        Dim stockQuote As [Decimal] = [Decimal].Parse(quoteNode.Attributes("lastTrade").Value, CultureInfo.InvariantCulture)  
        Dim lastUpdated As DateTime = DateTime.Parse(quoteNode.Attributes("lastUpdated").Value, CultureInfo.InvariantCulture)  
        Dim change As [Decimal] = [Decimal].Parse(quoteNode.Attributes("change").Value, CultureInfo.InvariantCulture)  
        Dim dailyMaxRange As [Decimal] = IIf(quoteNode.Attributes("dailyMaxRange").Value = "N/A", 0D, [Decimal].Parse(quoteNode.Attributes("dailyMaxRange").Value, CultureInfo.InvariantCulture))  
        Dim dailyMinRange As [Decimal] = IIf(quoteNode.Attributes("dailyMinRange").Value = "N/A", 0D, [Decimal].Parse(quoteNode.Attributes("dailyMinRange").Value, CultureInfo.InvariantCulture))  
         
        Return New Quote(stockTicker, stockQuote, lastUpdated, change, dailyMinRange, dailyMaxRange)  
    End Function 
 
 
    Private Function GetQuoteData(ByVal dataStream As Stream) As Quote  
        Dim buffer As String = Nothing 
        Dim sr As New StreamReader(dataStream)  
        Try 
            buffer = sr.ReadToEnd()  
        Finally 
            sr.Dispose()  
        End Try 
 
        buffer = buffer.Replace("""", "")  
        buffer = buffer.Replace(ControlChars.Cr + ControlChars.Lf, "")  
 
        Dim bufferList As String() = buffer.Split(New Char() {","c})  
        Dim quote As Quote = GetQuote(bufferList)  
 
        Return quote  
    End Function 
 
    Private Function GetQuotesData(ByVal xmlData As StringAs List(Of Quote)  
        Dim xmlDocument As New XmlDocument()  
        xmlDocument.LoadXml(xmlData)  
 
        Dim quotes As List(Of Quote) = New List(Of Quote)  
        Dim quote As Quote = Nothing 
        Dim quoteNode As XmlNode  
        For Each quoteNode In xmlDocument.DocumentElement.ChildNodes  
            quote = GetQuote(quoteNode)  
            quotes.Add(quote)  
        Next quoteNode  
 
        Return quotes  
    End Function 
 
 
    Private Sub SerializeQuotesData(ByVal quotes As List(Of Quote))  
        Dim str As StringBuilder = New StringBuilder("<quotes>")  
        Try 
            Dim quote As Quote  
            For Each quote In quotes  
                str.Append("<quote ")  
                str.Append("stockTicker=""" & quote.StockTicker & """ ")  
                str.Append("lastTrade=""" & quote.StockQuote.ToString(CultureInfo.InvariantCulture) & """ ")  
                str.Append("change=""" & quote.Change.ToString(CultureInfo.InvariantCulture) & """ ")  
                str.Append("lastUpdated=""" & quote.LastUpdated.ToString("MM/dd/yyyy HH:mm:ss") & """ ")  
                str.Append("dailyMaxRange=""" & quote.DailyMaxRange.ToString(CultureInfo.InvariantCulture) & """ ")  
                str.Append("dailyMinRange=""" & quote.DailyMinRange.ToString(CultureInfo.InvariantCulture) & """ ")  
                str.Append(" />")  
            Next quote  
        Catch e As Exception  
        End Try 
        str.Append("</quotes>")  
        SessionQuotesData = str.ToString()  
    End Sub 
End Class 

2 Answers, 1 is accepted

Sort by
0
Tracy Cole
Top achievements
Rank 1
answered on 28 Jul 2009, 08:44 PM
I'm still trying to figure this out on my own and I'm focusing in on the GetQuoteData function, which is parsing the stream based on the comma.   What I think I need is a function that will work with a CSV that contains quotes in addition to the comma delimiters.    For example, the Yahoo CSV for the S&P 500 looks like this:

"S&P 500 INDEX,RTH",979.62,"7/28/2009","4:42pm",-2.56,981.48,982.35,969.35,4272553984





The StockQuoteService as written bombs on the name since it has a comma in it.
0
Nikolay Rusev
Telerik team
answered on 03 Aug 2009, 10:47 AM
Hello Tracy,

The demo simply illustrates possible way of binding RadGrid it is really out of it's scope to demonstrate how to parse any data returned from service.

However for your scenario you can use the following code to parse CSV format:
protected void Page_Load(object sender, EventArgs e)  
    {  
           string s = @"""S&P 500 INDEX,RTH"",979.62,""7/28/2009"",""4:42pm"",-2.56,981.48,982.35,969.35,4272553984";  
           List<string> parsedData = ParseData(s);   
    }  
 
    public List<string> ParseData(string data)  
    {          
        Regex reg = new Regex(@"\s*(""[^""]*""|.*?)\s*,", RegexOptions.Compiled);  
        return reg.Split(data).Where(str=>str != string.Empty).Select(str=>str).ToList();          
    } 


I hope this helps.

Regards,
Nikolay
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
Tags
Grid
Asked by
Tracy Cole
Top achievements
Rank 1
Answers by
Tracy Cole
Top achievements
Rank 1
Nikolay Rusev
Telerik team
Share this question
or