Obtaining data from RSS feeds

The RSS feeds (Really Simple Syndication) are a popular and standardized way of presenting news, blog entries, and other content available at websites. You can read data from them directly in the web browser with the usage of built-in viewers or additional websites that aggregate data even from many channels, as well as by external RSS readers, which can be run on various platforms, including PCs, tablets, and mobile phones. The feeds can be easily recognized by their icon that is composed from a few white radio waves located at the orange square with rounded corners.

The RSS document is created in XML format. The sample one, containing information about the progress of the Space Aim 3D development, is presented as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
  <channel>
    <title>Space Aim 3D</title>
    <description>News about Space Aim 3D</description>
    <link>http://jamro.biz/spaceaim3d</link>
    <pubDate>Mon, 11 Mar 2013 12:00:00 GMT</pubDate>
    <item>
      <title>Geolocation and augmented reality!</title>
      <description>With the current version of the Space Aim 3D         game, we can easily see where are other players in the vicinity (if they agree to send location data).</description>
      <author>Marcin Jamro</author>
      <pubDate>Mon, 11 Mar 2013 12:00:00 GMT</pubDate>
      <guid>news-2</guid>
    </item>
    <item>(...)</item>
  </channel>
</rss>

The correct RSS file (in Version 2.0) has the rss root node that contains the channel one. It specifies metadata of the channel, as well as stores data of its items. Each item represents a single information (for example, news or blog entry) published at the website. In the preceding example, the feed contains just two items. However, new ones can be easily added by placing additional item nodes.

According to the specification, the channel node requires three child nodes, namely title (a name of the feed), description (a short information about the channel), and link (an address to the website, whose content is included in the feed). Apart from them, some other elements can be added that can specify the publication date, language, and other details.

Each item node has to contain the title or the description node. You can also store other data such as the link, author information, as well as entry categories.

Implementation

In this part, you will learn how to make improvements in the Web screen that makes it possible to read the latest news from the project's RSS feed. Its title, description, and publication date will be presented in the Latest news part, as shown in the following screenshot:

Implementation

News.cs

At the beginning, you create a new class (inside the Models directory) representing the single news read from the feed. The class is named News and contains three public properties, namely Title, Description, and Date. Apart from them, you define the constructor, which allows to set values of all these properties, as shown in the following code:

public class News
{
  public string Title { get; set; }
  public string Description { get; set; }
  public DateTime Date { get; set; }
  public News(string title, string description, DateTime date)
  {
    this.Title = title;
    this.Description = description;
    this.Date = date;
  }
}

WebPage.xaml

Some minor modifications are necessary in the XAML code of the Web screen. Here, you add three TextBlock controls, just after the header of the Latest news group:

<TextBlock Text="[ localized string ]"
  Style="{StaticResource SA3DBoxHeader}" />
<TextBlock Text="{Binding LatestNews.Title}" TextWrapping="Wrap"
  FontWeight="Bold" FontSize="24" />
<TextBlock Text="{Binding LatestNews.Description}"
  TextWrapping="Wrap" FontSize="22" />
<TextBlock Text="{Binding LatestNews.Date}" FontSize="20"
  HorizontalAlignment="Right" Margin="0 0 0 10" />

The first added element presents the title, the second shows the description, while the other presents the publication date. It is worth mentioning that Text properties of all these controls are bound to particular properties of the LatestNews object from the view model.

You should also specify a style for all TextBlock controls (inside the page resources), which sets the SA3DFontBrush static resource as the Foreground.

WebViewModel.cs

Other changes are necessary in the view model class for the Web page. At the beginning, you set an address to the RSS feed as a value of the FEED_URL constant. You can create a new constant value in the GameHelpers class and use it here, as presented in the following line:

private const string FEED_URL = GameHelpers.RSS_FEED;

Then, you should create a new public property named LatestNews, together with a supporting private field. The property allows to get and set the News instance that represents the last information read from the RSS feed.

The ReadLatestNews method starts downloading the content of the RSS feed:

private void ReadLatestNews()
{
  WebClient webClient = new WebClient();
  webClient.DownloadStringCompleted +=
    this.WebClient_DownloadStringCompleted;
  webClient.DownloadStringAsync(new Uri(FEED_URL));
}

You can download the XML file using the WebClient class. To do so, you create its new instance, set a method called when the download is finished, and call the DownloadStringAsync method, passing the address as a parameter.

The WebClient_DownloadStringCompleted method is called when the file (which address was specified while calling the DownloadStringAsync method) is downloaded. A code of this method is as follows:

private void WebClient_DownloadStringCompleted(object sender,
  DownloadStringCompletedEventArgs e)
{
  if (e.Error != null)
  {
    this.LatestNews = new News(
      AppResources.WebLatestNewsErrorTitle,
      AppResources.WebLatestNewsErrorMessage,DateTime.Now);
    return;
  }
  XDocument document = XDocument.Parse(e.Result);
  XElement item = document.Descendants("item").FirstOrDefault();
  if (item != null)
  {
    string title = item.Element("title").Value;
    string description = item.Element("description").Value;
    DateTime date = DateTime.Parse(item.Element("pubDate").Value);
    this.LatestNews = new News(title, description, date);
  }
}

If the process of downloading is finished successfully, you create a new XDocument instance representing the XML content of the downloaded file. Then, you get the first item from the RSS document, with the usage of LINQ. It is achieved by calling the Descendants method (on the XDocument instance), which returns a collection of XElement instances (each one represents a single XML element) with a specified name (item in your case). To return only the first item, you use the FirstOrDefault extension method. It returns the first element from the collection (if it contains any items) or null. You should not forget to add the using directive for System.Linq.

When the item variable contains data of the XML node representing the last RSS item, you read its title, description, and publication date. It is worth mentioning that the date for item is stored in a way defined in RFC 822 (for example, Mon, 11 Mar 2013 12:00:00 GMT). However, it can be easily parsed into the DateTime instance by the static Parse method. Then, you create the News instance and assign it to the LatestNews property.

Whenever you navigate to the Web screen, you want to download the latest news. Thus, at the end of the OnNavigatedTo method, you call the ReadLatestNews one:

public void OnNavigatedTo(NavigationEventArgs e)
{(...)
  this.ReadLatestNews();
}

Currently you can launch your game in the emulator or on the phone and navigate to the Web screen. You should see the latest news read directly from the RSS feed! In case of any errors (such as incorrect feed address), you will receive a suitable information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.186.79