DCSIMG
Creating a simple RSS reader for Windows 8. [Tutorial] - Eloy's blog - Site Root - StudentGuru

Creating a simple RSS reader for Windows 8. [Tutorial]

[Click here for the source code: https://skydrive.live.com/redir?resid=D6054CB0221449CF!282&authkey=!AC4qLsv6qK43fWo]

Let’s start our first Windows 8 App, a simple as possible RSS Reader, with the use of Microsoft Visual Studio 2012 and the Blend for Visual Studio 2012. We are going to use the C# language in combination with XAML, for the UI rendering.

Open the Visual Studio and select from the menu bar File -> New -> Project. In that point you will see under the “Templates” list, all the available project types you can create with your default Visual Studio language. So if C# is not the language that your Visual Studio is optimized for, at the initializing of your installation, navigate to the “Other Languages” List and select “Visual C#”.

 

Now select “Blank App (XAML)” in order to create a new Windows 8 Store App, and give the name “RSSReaderApp”. (You can use whatever name you want, just remember to keep your project namespace consistent with the below code examples.)

Press Ok. Now you have a new project, ready for the RSS implementation!

We are going to keep this project as simple as possible but it is a nice idea to have some things ready, if you want to add later some useful Windows 8 feature’s as Layout Awareness. So in order to be able to improve your app’s behavior, easy and fast in the future we are going to do something very simple:

Right Click on the “MainPage.xaml” page, in your Solution Explorer, and then select “Delete”. We are going to delete this page and replace it with a new Page with Layout Awareness. This can save us time and effort, when we would like to implement a Snap Mode in our App for example, as this type of Pages have a lot code already implemented for us.

 

I would suggest that in every new project you create, just do these easy steps, as they are going to save you a lot of time when you decide to improve your app.

Now right click on your project name, navigate to the “Add” panel and select “New Item” (or just click Ctrl+Shift+A). Now select “Basic Page”. This kind of page has many useful features already implemented for you, so just remember to name it as “MainPage.xaml”, in order to avoid further corrections in the Project Properties.

 

After that a dialog window occurs, press “Yes”. This is necessary in order to allow Visual Studio to add all the required files for you automatically.

 

After that you will probably notice that your project has at least one error, even though you didn’t even write a single line of code! Don’t worry this is normal and the solution is much simpler than you thought. Just navigate to the “Build” Button, in the Menu Bar and Select “Build Solution” (or just click F6), if this project is the only Project in the Solution, or select “Build RSSReaderApp” (or just click Shift + F6).

 

In order to take advantage of the Layout Awareness in this page, just type the following command in the import section of your page:

using RSSReaderApp.Common;

 With this import you can use the Common Folder of your project, which contains all the files the Visual Studio automatically added before. Now rebuild your project.

 

Ok so far. Now let’s change some basic attributes of our App, within the Visual Studio, before we create a simple and basic template that will hold our RSS feeds.

In your “MainPage.xaml” you can easily change your App Name, from the XAML code.

In Windows Store Apps, there is extensive use of Static Resources in order to have a more organized and powerful way to manage your File or Project resources. Just find the above code section, in this XAML file and change the “AppName” attribute, in the name you want. Here my choice is “My RSS Reader”.

 

You can also change the Background Color of your app, very easy from the Property Explorer of your page’s main Grid. Just make sure that you have activated the current page (just click on the Graphic Designer), and select from the “Brush” List, the color you want. Here I randomly pick turquoise.

Enough with Visual Studio for now, let’s create some very basic UI Elements, in our MainPage.xaml with the use of Blend. Right click on the “MainPage.xaml” and select “Open in Blend…” as shown below.

 

In the Blend, make sure that the Design Workspace is activated (Check from Window -> Workspaces), adjust your zoom level in order to work effectively with your page and select a new Grid object (right click), as shown below:

 

Now draw a new Grid in that page, and make sure it has the size attributes shown below. This is the Grid in which we will place a ListView with all our feeds and another one Grid with TextBoxes, that will keep all the details of a selected RSS feed. Make sure that your new Grid has the below Layout Attributes, at the Properties Window:

 

The page should seem like this until now:

 

Now navigate to the “Asset” List, and select a ListView Item.

 

Draw it to your page and make sure that it has the below Layout Properties. Also it is important that you don’t forget to give the name “listView1” in your new ListView object, as you must refer to this object within the C# code, in order to bind your feeds Data with the UI.

 

 After that we are going to create a new Data Template, in order to hold all the necessary elements we need for each feed representation in the ListView. So right click on the ListView you just created and follow the above steps:

 

In the Input Dialog, press Ok.

 

What you see at this point is an empty Grid, which will hold all the elements we want to place in, for our feed graphical representation. In this project we use the below Layout Settings:

 

Here you can place some TextBoxes in order to show only the basic info to the user, and we will create another Grid, as mentioned before, in the left side of our Page, where all the available feed data will be displayed there.

The best option about the TextBoxes sizes, Text Wrapping attributes etc, depends basically on the selected feed URI, as also what you want to show for every feed on that List. You can refer to the provided completed project, for the sizes selected at this example, but what the Data Template will contain is mainly your decision.

Here is a snapshot of the current project Data Template:

 

In the same way as before, we will create another Grid which will hold the selected Item’s specific details. Select a new Grid and draw one in your Page. Make sure that the above Layout Properties are selected for this Grid:

 

As said before, the choice of what you want to place inside this Grid is yours. If you want to use the same Layout as here, you can always refer to the code of the given “MainPage.xaml” or you can just import the whole page in your project.

The final result after, changing a little bit the colors of our elements, the Font Colors etc would be something like this:

 

Now let’s write some more code, in order to handle our RSS Feeds. We can have access to the RSS contents, easily and fast, with the use of “Syndication Client”. This feature is provided by Microsoft under the namespace “Windows.Web”.

So right click on your project name, navigate to the “Add” panel again, and select “New Item” (or just click Ctrl+Shift+A as said before). We are going to create a new C# Class that will retrieve our Feeds. Select from the Code Section, a C# Class and rename it as “Util.cs”. Now press “Add”.

All right so far, now let’s import the Namespace “Windows.Web.Syndication” in order to retrieve our feeds. Type the following command, in the namespace import section:

using Windows.Web.Syndication;

Now we need to create the class that will hold the contents of our feeds. Let’s name this class as “FeedItem”, and let’s include in this all the necessary Properties for smooth and fast Data Access. Copy the following code, after the end of the “Util” Class but inside your project’s Namespace:

public class FeedItem
{
    public string Content { get; set; }
    public string Author { get; set; }
    public string Title { get; set; }
    public Uri Link { get; set; }
    public DateTime PubDate { get; set; }
}

As you can see, we will keep all the necessary information about each one of our feeds, such as the Content of our feed – its actual Information as a text -, the Title of the feed, the Publishing Date etc.

Now it’s time to build a method that will do all the “work” easily and fast, using the already implemented methods, provided by the Syndication Client Class. As this whole project is about building a Windows Store App –using of course the brand new .NET 4.5- we will use, and build on our own, an async method in order to achieve fast and reliable access to Web Contents. For more information about Async Programming, the new features of the .NET 4.5 and almost everything you want to know about building Windows Store Apps, please refer to the above links:

http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

http://msdn.microsoft.com/en-us/library/ms171868.aspx

http://msdn.microsoft.com/en-us/windows/apps/br229512.aspx

Copy and Paste the following static Async Method, inside the Util Class you just created:

public static async Task<List<FeedItem>> getFeedsAsync(string url)
{
       //The web object that will retrieve our feeds..
       SyndicationClient client = new SyndicationClient();

       //The URL of our feeds..
       Uri feedUri = new Uri(url);

       //Retrieve async the feeds..
       var feed = await client.RetrieveFeedAsync(feedUri);

       //The list of our feeds..
       List<FeedItem> feedData = new List<FeedItem>();

       //Fill up the list with each feed content..
       foreach (SyndicationItem item in feed.Items)
       {
             FeedItem feedItem = new FeedItem();
             feedItem.Content = item.Summary.Text;
             feedItem.Link = item.Links[0].Uri;
             feedItem.PubDate = item.PublishedDate.DateTime;
             feedItem.Title = item.Title.Text;

             try
             {
                 feedItem.Author = item.Authors[0].Name;
             }
             catch(ArgumentException)
             { }

             feedData.Add(feedItem);
         }

         return feedData;
    }
}

Now let’s see what does the above method provides us and how:

First of all you can see that the method signature is Static. This is necessary as we will call it from the “MainPage.xaml.cs” Class, in order to update correctly the UI Elements we created before. Another thing that you probably notice is that the method returns a List with “Feeds” – and to be more specific, a Task that will give as a List with Feeds, as soon as all the feeds are available – For more information about the signatures, the operation and the naming convention of an Async method, please refer to the above links.

The operation of this method is simple; It uses the RetrieveFeedAsync() Async method - provided by the SyndicationClient Class- in order to  retrieve all the RSS feeds we want, by the given URL. After that we just create a new List with all the RSS Feeds we just received from the SyndicationClient Class. The interesting fact here is, as you can see, that the SyndicationClient Class provides us all the necessary methods to save, easily and fast, all the Data we want in our Feed Class. Notice that we use a try – catch block when we initialize the Author Property of our feeds, as some RSS feeds may not provide the following Data Section in some Countries.

Retrieving RSS feeds, in a safe and fast way, was never more fun and easy!

We’ve done with this Class. Let’s bind our Data to the ListView we created before, and finish our RSS Reader. Now open the “MainPage.xaml.cs” and Copy, Paste the following code Section:

//The url of our rss..
const string url = "http://www.naftemporiki.gr/news/rsscateg.asp?categ=FIN";

This string constant will hold the URL of our feeds, with which we will call the getFeedsAsync() method, we just created before.

We want to ensure that the feeds will be available as soon as the user Navigates to this page  in our App. (“MainPage.xaml”). So it’s a nice idea to ensure that behavior by loading the feeds in the 

OnNavigatedTo(NavigationEventArgs e) 

method, something that will help us to have all the feeds displayed “Up to Date”, even if we add more Pages in our App in the future.

So Copy and Paste the following Code Section in your MainPage Class:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
      base.OnNavigatedTo(e);

      List<FeedItem> feedData = await Util.getFeedsAsync(url);

      listView1.ItemsSource = feedData;
}

This method just creates a new List with FeedItems, simply by calling the getFeedsAsync() in the Util Class. Then we just “bound” the ItemsSource of our ListView with this List and the feeds will be available to the user! Notice the await keyword in front of our Async method call, as and the async keyword in the 

OnNavigatedTo(NavigationEventArgs e)

method.

Now in order to finish our App we must implement the Data Binding and the ListView Selection mechanism. First of all, make sure that you add the following commands to your Data Template code section, located in your “MainPage.xaml” page:

These three commands are Binding each of our feed Property we want to show to the user, in our ListView with the TextBlock we made for that specific property. We just assign the actual RSS Feed Data, to the Text Property of our TextBlocks.

Next, in the ListView declaration, in your Main Page XAML code, copy the following command:

 

This will enable us to use a simple “Item Click Event” in order to fill the second’s Grid TextBlocks, with the selected feed Information.

So select the Event Handler List, from the Properties Window of your ListView and double click on the “ItemClick” Event.

A new Event Handler has just been constructed and the last thing you have to do is to Copy and Paste the following commands in that method’s body:

var item = e.ClickedItem as FeedItem;

if (item == null) return;

TitleTxtBlock.Text = item.Title;
DateTxtBlock.Text = item.PubDate.ToString();
ContentTxtBlock.Text = item.Content;

Just make sure to adjust your Grid’s TextBlock’s names, with those you created to your project. You are now ready to run your App! Go to the “DEBUG” list in the Menu Bar, and select “Start Debugging” (or just press F5).

Here you are! This is how the given project looks like. You are free to customize the code as you wish!

 

Click here for the source code: https://skydrive.live.com/redir?resid=D6054CB0221449CF!282&authkey=!AC4qLsv6qK43fWo

 

  • Anonymous
    Anonymous

    thanks for the great tutorial ,

    I just want to know how to retrieve and view an image from a rss feed

    thanks

  • Hello,

    First of all I would like to thank you for your kind words and your feedback.

    As far it concerns your question, I could suggest you to try the above two solutions:

    1) If I’m not wrong, you can always try to retrieve the wanted Image from your RSS feed, as the value of the property “ImageUri”, available in each one of your “SyndicationFeed”  objects.

    (Also you may try to use the Debugger of your VS2012 instance, in order to explore and the rest values of your available properties.)

    2) The above solution may not work in your case, as long as this approach requires that your RSS Feed has the wanted image “embedded” in its data.

    So in that case I would suggest you to parse your RSS feed, with a custom function in order to retrieve your images.

    Below there is an example of the above idea:

    . . .

    private static string getImageRSS(SyndicationItem item)

           {

               try

               {

                   int startIndex = item.Summary.Text.IndexOf("src=");

                   var temp = item.Summary.Text.Substring(startIndex);

                   temp = temp.Remove(0, 5);

                   temp = temp.Split('>')[0];

                   temp = temp.Remove(temp.LastIndexOf('"'));

                   temp = temp.Remove(temp.LastIndexOf(".jpg"));

                   temp += ".jpg";

                   return temp;

               }

               catch (Exception)

               {

                   return "Assets/150x150.png";

               }

           }

    . . .

    So now you only have to parse each one of your “SyndicationItem” objects, and to retrieve your wanted image – If there is any of course.

    Hope I’ve helped.

    Regards,

    Eloy.

  • Anonymous
    Anonymous

    Thanks for the great tut,

    i am looking to find a way to feed an image on a picture box which is also being feeded from the RSS. Any tips would be helpfull

    thanks in advance

  • Hi,

    Thank you for your kind words.

    As far it concerns your question, first of all I would like to inform you that there is no “picture box” UI element available for Windows Store Apps, but you can of course use instead the “Image” Element –just like the “picture box” UI element available in Windows Forms applications.

    So I would propose you the below steps:

    1) First add the below property to your “FeedItem” class:

    “public string Image { get; set; }”

    2) In your “Util.getFeedsAsync(string url)” method add the below line, inside the try-catch block of your method’s body of course:

    “feedItem.Image = getImageRSS(item);”

    3) Now you can easily show your selected images, with exactly the same way as the other properties of your FeedItem class.

    As long as you have already assign your RSS feeds items list to your UI Container Element (here we use a ListView), the only thing that you have to add is an “Image” object in the “MainPage.xaml” page, and then to Bind the “Sourse” property of this Image to the wanted image of your RSS feed item object.

    (for eg in the above tutorial I’m talking about the “listview1” object. Please refer to the body of the “protected override async void OnNavigatedTo(NavigationEventArgs e)” in order to see this assignment.)

    So in the Data Template of your Container UI Element (here the ListView), you can just add the suggested object (“Image”) and everything will work fine now.

    <Image Source="{Binding Image}" HorizontalAlignment=”… " … />

    Please note that you have to adjust the other properties of your Image object (As the “HorizontalAlignment” property value) according to your UI configuration.

    I left them empty and incomplete on purpose, as long as I am trying to show you the general idea behind your question.

    Hope I’ve helped.

    Regards,

    Eloy.

  • Anonymous
    Anonymous

    I would like to thank for this wonderful tutorial, really it helped me a lot.

    But?

    How to add an image to listView1? Can you make it clear?

    We are just adding feedData from getFeedsAsync(url) method in OnNavigatedTo function. How to add "temp" which we returned in getImageRSS(item)?

    Thanks in Advance.

  • Hi,

    Thank you for your kind words.

    In order to be able to show your downloaded images, you have to explicitly implement your own DataTemplate object, assign it to the ItemTemplate property of the wanted UI Component (here the listView1) and finally to Bind the path of your images via the listView ItemsSource property.

    So you can alter the given Project‘s code by changing the DataTemplate of your ListView, simply by adding an Image UI element, as shown in my previous posts.

    To be more specific, please refer to the lines 16 -23 and 82 of the given “MainPage.xaml” page, and feel free to change whatever you need.

    I would also suggest you to take a look in the below links, as long as there you will find everything you need to know in order to implement your own Data Template, and to use the .NET Binding mechanism for further manipulation.

    msdn.microsoft.com/.../cc903947(v=vs.95).aspx

    msdn.microsoft.com/.../ms742521.aspx

    stackoverflow.com/.../windows-store-apps-listview-datatemplate

    stackoverflow.com/.../bind-images-to-a-listview-in-metro-app-win-8-app

    Hope I’ve helped.

    Best Regards,

    Eloy.

  • Anonymous
    Anonymous

    Thanks for the post, this helped me to finish a similar example, with Pivot

  • Hi,

    Thank you for your kind words.

    Glad I’ve helped!

    Best Regards,

    Eloy.