How to Build an RSS Feed Reader in Windows Phone 7 – Part I: Retrieving, Parsing, and Displaying Post Titles

474975762_67c1c8a5bf_o-300x300

One of the first applications that I write for a new platform to learn the ropes is an RSS reader.  That rule holds true for Windows Phone 7.  The great thing about the Windows Phone 7 SDK and the .NET 4.0 platform is that everything you need to work with RSS or any other syndication feed is ready for you right out of the box!  With Android development, you need to parse the XML and return values yourself.  For just reading an RSS feed, it’s a nightmare.  The references don’t, however, show up in Visual Studio 2010 automatically, so you’ll need to add them manually.  I’ll go over it all in this guide to programming RSS feeds in Windows Phone 7.

If you’re creating a Windows Phone 7 app for the first time, you’ll notice that there are two types of applications that you can create:

  • Silverlight (List/Form/Standard Graphics)
  • XNA (Enhanced/Custom Graphics)

XNA applications are great for games or fancy-pants apps, but not for RSS readers.  For our blog/RSS app, we’ll need to just select the standard Silverlight list template.  This gives us a great head start with the UI that we can use as the main menu of post titles (and more that we’ll use in later posts).

Now for the magic!  If you’ve read my other post on how to read RSS feeds in Android, you’ll be relieved to know that Windows Phone 7 is leaps and bounds easier than Android!  Microsoft was kind enough to give us System.ServiceModel.Syndication, which contains absolutely everything you need for dealing with RSS feeds and xml-based syndication.  However you must add System.ServiceModel.Syndication.dll manually as Visual Studio 2010 does not show it in the list of references out of the box.

To add System.ServiceModel.Syndication.dll:

  1. Right-click References in the under the Windows Phone 7 project in the Solution Explorer.
  2. Select Add Reference
  3. Go to the Browse tab (Note: This may be added to the .NET tab as usual in future releases of the Windows Phone 7 SDK.  Keep that in mind if you’re reading this…from the FUTURE!)
  4. On your C: (or equivalent) drive, browse to \Program Files\Microsoft SDKs\Silverlight\v4.0\Libraries\Client
  5. In the list, select System.ServiceModel.Syndication.dll and click OK.

Now you’re all set to work with RSS feeds!  Everything we do in this post will be working with the MainPage.xaml and its MainPage.xaml.cs code behind file.  First, let’s add some code to the OnNavigatedTo method in the MainPage.xaml.cs file:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string url = "http://feeds.feedburner.com/blogryanhayesnet";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.BeginGetResponse(ResponseHandler, request);
}

This little piece of code does a few things whenever the Windows Phone 7 application hits the MainPage:

  • Sets the RSS feed URL of the feed you want to display.
  • Creates a new HttpWebRequest with that url to fetch.
  • Starts an asynchronous request to grab the feed.

You’ll notice that I bolded asynchronous.  This is because if you’ve done a lot of web requests in the past, you just shoot the request and immediately get the response in the next line.  With phones, however, your connection can come and go, and from different sources.  For this reason the HttpWebRequest is split into two parts.  First, this request, which fires off a .BeginGetResponse(ResponseHandler, request);.  Once the request is completed, an event fires, which is what the ResponseHandler part is for.  This method that we need to create fires as soon as the RSS feed is received, and we’ll also use that method to update the contents of the MainListBox with the items that we get back!  Let’s take a look at it now:

The first few lines of the method make sure the HttpWebRequest came back with an OK status and gets the response information.  If everything checks out, then we proceed to parsing the RSS feed that was returned.  First, we use XmlReader to get the response as an XML document. Once we have that, we load the reader into a new Syndication Feed.  The SyndicationFeed is basically a wrapper around a standard XML object that already has all the properties ready to grab that you would expect in an RSS feed and its posts! Awesome! From here you can the SyndicationFeed however you want.  For my blog application, I chose to set the SyndicationFeed object as the ItemsSource for the MainListBox in my UI.

From here, we’re almost done.  The last thing that we need to do is set the ItemText and DetailsText’s Text properties to bind to the Title property in the Feed’s list of Items.  For this, I bound both to just the Title text – take a look:

And that’s it! Seriously, that’s all you need to get started with reading RSS feeds in Windows 7.  In part II of this series I’ll finish up the project and show you how to maneuver to a second page and show the full post in the blog app.

Ryan Hayes

Ryan is a Microsoft MVP award winner with over eight years of software experience, working with big-name clients such as Discovery Channel, AOL, Toyota, and the National Academy of Sciences. Ryan has helped teams deliver award-winning applications that drive business processes, site traffic, and profit, putting his experience and creativity to work to build amazing solutions for the enterprise web, desktop and mobile platforms.

  • Adamcarter93

    Here is my code:

    namespace T3_RSS_Reader
    {
    public partial class MainPage : PhoneApplicationPage
    {
    public MainPage()
    {
    InitializeComponent();

    SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
    }

    protected override void OnNavigatedTo(Microsoft.Phone.Navigation.PhoneNavigationEventArgs e)
    {
    base.OnNavigatedTo(e);
    string url = “http://feeds.feedburner.com/T3/news”;
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
    request.BeginGetResponse(ResponseHandler, request);

    }

    private void respoonseHandler(IAsyncResult asyncResult)
    {
    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

    if (response.StatusCode == HttpStatusCode.OK)
    {
    XmlReader reader = XmlReader.Create(response.GetResponseStream());
    SyndicationFeed newFeed = SyndicationFeed.Load(reader);
    MainListBox.Dispatcher.BeginInvoke(delegate
    {
    MainListBox.ItemsSource = newFeed.Items;
    });
    }
    }
    }
    }

    But for some reason I’m getting the errors:

    Error 1 The name ‘ResponseHandler’ does not exist in the current context c:usersadam carterdocumentsvisual studio 2010ProjectsT3 RSS ReaderT3 RSS ReaderMainPage.xaml.cs 30 38 T3 RSS Reader
    Error 2 The type or namespace name ‘XmlReader’ could not be found (are you missing a using directive or an assembly reference?) c:usersadam carterdocumentsvisual studio 2010ProjectsT3 RSS ReaderT3 RSS ReaderMainPage.xaml.cs 41 17 T3 RSS Reader
    Error 3 The name ‘XmlReader’ does not exist in the current context c:usersadam carterdocumentsvisual studio 2010ProjectsT3 RSS ReaderT3 RSS ReaderMainPage.xaml.cs 41 36 T3 RSS Reader
    Error 4 The type or namespace name ‘SyndicationFeed’ could not be found (are you missing a using directive or an assembly reference?) c:usersadam carterdocumentsvisual studio 2010ProjectsT3 RSS ReaderT3 RSS ReaderMainPage.xaml.cs 42 17 T3 RSS Reader
    Error 5 The name ‘SyndicationFeed’ does not exist in the current context c:usersadam carterdocumentsvisual studio 2010ProjectsT3 RSS ReaderT3 RSS ReaderMainPage.xaml.cs 42 43 T3 RSS Reader

    I have also typed the exact ‘MainListBox’ code above into the xaml

    thanks :)

    • http://ryanhayes.net Ryan Hayes

      Hey Adam!

      For the first error, it looks like it’s just a typo. The line “request.BeginGetResponse(ResponseHandler, request);” is the method that starts the request to get the RSS feed, and ResponseHandler is the method it will look to call as soon as it gets a response. All you need to do is change the name of your “respoonseHandler” method to be exactly the same. That way it’ll be able to call it.

      Errors 2-5 are pretty simple to clean up. Just add the proper using statements for them at the top of the .cs file.

  • Luiz

    My error trying your code: Error 1 ‘RSS.MainPage.OnNavigatedTo(Microsoft.Phone.Controls.NavigatingEventArgs)': no suitable method found to override

    Any glue?

    • http://ryanhayes.net Ryan Hayes

      Can you post more of your code? It’s hard to tell what the error is from just the output message.

  • Maze

    I get these errors

    Error 1 Expected class, delegate, enum, interface, or struct
    Error 2 Expected class, delegate, enum, interface, or struct
    Error 3 Type or namespace definition, or end-of-file expected

  • Casey_boy

    Thanks for the tutorial. BIG problem with this though – if the device has no internet connection (i.e. for test purposes: flight mode or yank out the internet to your PC) the app will just crash.

    Visual studio indicates that say that a WebException was unhandled. “The remote server returned an error: NotFound”.

    Any ideas on how to fix this?

    • Casey_boy

      OK, I think I’ve found a way to fix this using catch(WebException):

      private void ResponseHandler(IAsyncResult asyncResult)
      {

      try
      {

      HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
      HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

      if (response.StatusCode == HttpStatusCode.OK)
      {
      XmlReader reader = XmlReader.Create(response.GetResponseStream());
      SyndicationFeed newFeed = SyndicationFeed.Load(reader);
      twitterListBox.Dispatcher.BeginInvoke(delegate
      {
      mainListBox.ItemsSource = newFeed.Items;
      });
      }
      }

      catch (WebException) { }
      }

      Hopefully that’ll hold and hopefully it’ll help anyone who reads this. You could of course add something useful in the catch – but, for me, it wasn’t required to do so.

      • http://ryanhayes.net Ryan Hayes

        Good catch. I just didn’t test disconnecting when I wrote up the tutorial, but yea, catching the exception will do the trick. I wish there was an easier way to test the network disconnecting on the emulator besides yanking the ethernet cable out of the computer. :-/