I stopped doing meaningful Windows development many moons ago, however, I was recently attempting to setup a simple test application that would send and receive data via a URI. I was taking advantage of existing code and missed the opportunity to do it the right way so I am taking the opportunity to do it the right way here. In this example (inspired by Scott Gu) I am using the WebClient class and the Twitter API. I am using DownloadString*, however, there is also a DownloadData* which returns a byte array for processing.

WebClient mt = new WebClient();
mt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(mt_DownloadStringCompleted);
mt.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + _name));

I am primarily using .NET 1.1 at work and so my options would be limited in terms of processing the response. As I am currently testing out Visual Studio 2010 Express, we can and will use LINQ to SQL to process the XML response.

void mt_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null)
        return;

    XElement tweets = XElement.Parse(e.Result);
    var sometweets = from twt in tweets.Descendants("status")
                     select new Tweet
                     {
                         ImageSource = twt.Element("user").Element("profile_image_url").Value,
                         Message = twt.Element("text").Value,
                         UserName = twt.Element("user").Element("screen_name").Value
                     };
}

public class Tweet
{
    public string UserName { get; set; }
    public string Message { get; set; }
    public string ImageSource { get; set; }
}

That is it really, if you need to pull string or binary data from a URI in the Windows world WebClient is your class in the world of .NET. An opportunity missed but I feel better for having got it off my chest here.

Related Links:



Comment Section

Comments are closed.