WebClient – Windows Phone Services Consumption – Part 1


At Orlando and Fort Lauderdale 2011 CodeCamps I was privileged to deliver talks on "Consuming Services on Windows Phone 7".  Both locations were pretty much standing room only for the sesions. During the talks I realized there is an interest in the audiences for some blueprints aroundWindows Phone topics on service consumption. This is the first part of a series of articles I'm going to write discussing consuming services on Windows Phone 7. I'll update this doc as well as the others with a table of contents on the series as more articles come out.

During the Windows Phone Services Consumption series, we'll explore a number of APIs (REST, OData, RSS, ATOM, and more) out there using a variety of formats. Hopefully find some cool public APIs as well that perhaps can be used in your applications as well.

Got some APIs you want tickled? Let me know. 

First step.  Key to hitting any web APIs on Windows Phone is knowing how pull in data via HTTP. Two classes are avaialble to us, WebClient, and HttpWebRequest. Let's explore both and see what works best for us.  In this first post we're going to see how to call WebClient.

WebClient is a simplified client wrapping up a HttpWebRequest internally. WebClient is very simple to use and doesn't require much effort to consume content. WebClient does return on the primary UI thread, however.  Returning on the UI thread, then parsing data on the main UI thread can lead to performance issues. WebClient also doesn't offer access to some of the raw http protocol elements like HttpWebRequest does.

Sample WebClient Wireup
We're going to use the WebClient to simply scrape the HTML off the MSDN home page. Nothing more or less. Let's do a step by step to wiring this up.

Step1: Create a new Windows Phone Portrait Project
Step2: Modify MainPage.xaml, change the ContentPanel from a Grid to StackPanel, and make it match what's below.

        <StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button Content="Call WebClient" Width="250" Click="Button_Click" />
            <TextBlock Text="Web Client Target:" Style="{StaticResource PhoneTextNormalStyle}" Foreground="{StaticResource PhoneAccentBrush}" />
            <TextBlock Text="http://msdn.microsoft.com" TextWrapping="Wrap" Margin="20,0,0,0" x:Name="TextBlockTargetUri" />

            <TextBlock Text="Elapsed Time:" Style="{StaticResource PhoneTextNormalStyle}" Foreground="{StaticResource PhoneAccentBrush}" />
            <TextBlock Text="tbd" TextWrapping="Wrap" Margin="20,0,0,0" x:Name="TextBlockElapsedTime" />

            <TextBlock Text="WebClient Call Results:" Style="{StaticResource PhoneTextNormalStyle}" Foreground="{StaticResource PhoneAccentBrush}" />
            <TextBlock x:Name="TextBlockResults" Text="results go here" Margin="20,0,0,0" TextWrapping="Wrap"/>

Next the code. Match up the steps given to the code block below.

Step3: Setup an instance of the WebClient at a class level (I like my m_vars from my MFC days, leave me alone!).
Step4: Initialize the WebClient, and setup a DownloadStringCompleted handler for it. The handler will be called when the WebClient call is complete
: If you type in m_myWebClient.DownloadStringComplete+= then hit tab,tab Visual Studio will generate an empty function for you.
Step5: When DownloadStringCompleted returns, grab the string from the result. Very easy....

    public partial class WebClientPage : PhoneApplicationPage
        // step3 step3 step3
        private WebClient m_myWebClient;

        public WebClientPage()
            // step4 step4 step4
            m_myWebClient = new WebClient();
            m_myWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(myWebClient_DownloadStringCompleted);

        private void Button_Click(object sender, RoutedEventArgs e)
            TextBlockResults.Text = string.Empty;
            m_myWebClient.DownloadStringAsync(new System.Uri(TextBlockTargetUri.Text));

        // step5 step5 step5
        void myWebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
            TextBlockResults.Text = e.Result;

Plus-side of WebClient. Very easy to wireup, very easy to process the results.
Negatives of WebClient - Blocking the main UI thread when returning, and limited programmability.

How to remedy some of the downsides?  We'll see in the next article on HttpWebRequest .

Consuming Windows Phone Services Series
Part 1 - Web Client Basics - http://blogs.msdn.com/b/devfish/archive/2011/04/06/webclient-windows-phone-services-consumption-part-1.aspx
Part 2 - HttpWebRequest Fundamentals - http://blogs.msdn.com/b/devfish/archive/2011/04/07/httpwebrequest-fundamentals-windows-phone-services-consumption-part-2.aspx
Part 3 - Parsing REST based XML Data - Part A - Single Result - http://blogs.msdn.com/b/devfish/archive/2011/05/05/consuming-geocode-yhoo-api-via-rest-windows-phone-services-consumption-part-3.aspx
Part 4 - Parsing REST based XML Data - Part B - Multiple Results - http://blogs.msdn.com/b/devfish/archive/2011/05/10/consuming-geocode-yhoo-api-via-rest-dealing-with-multiple-results-part-4.aspx

Comments (2)
  1. Jason says:

    Is there a reason for instantiating the WebClient object twice?  

  2. sdhconsulting says:

    How does this asynchronous call block the UI thread?

Comments are closed.

Skip to main content