Reading RSS powered by FeedFlare™ using ASP.NET and LINQ

Posted by: Suprotim Agarwal , on 11/4/2008, in Category ASP.NET
Views: 27754
Abstract: I have been posting articles on the LINQ to XML series lately. Before posting the 3rd and final part of the series, I thought of showing you a small application built on LINQ to XML. In this article, we will see how to read a RSS Feed using LINQ to XML.
Reading RSS powered by FeedFlare™ using ASP.NET and LINQ
 
I have been posting articles on the LINQ to XML series lately. Before posting the 3rd and final part of the series, I thought of showing you a small application built on LINQ to XML. In this article, we will see how to read the RSS Feed of dotnetcurry.com using LINQ to XML. I assume you are familiar with the new features of C# 3.0 or VB 9.0. If not, check this article for C# users Getting Ready for .NET 3.5 and LINQ – Exploring C# 3.0 – Part I. VB.NET users can learn about the new features over here.
What is RSS?
RSS stands for Really Simple Syndication. It is a format used to publish regularly updated web content such as blogs, articles, news sites etc. Now if you happen to visit a website regularly and have to often to go that website to physically to check if there is some new content available, then RSS feed is what you are looking out for. If that website provides RSS feed, all you need to do is subscribe to it. You can then use any RSS reader (like the one we will be building) which displays frequently updated content. Handy, isn’t it!
Note: If you like visiting dotnetcurry.com and check for new articles, one option of doing so would be to subscribe to my RSS feed over here or get updates via Email over here.
What is FeedFlare?
According to FeedBurner, a FeedFlare™
"..Give your subscribers easy ways to email, tag, share, and act on the content you publish by including as many or few of the services listed below. FeedFlare™ places a simple footer at the bottom of each content item, helping you to distribute, inform and create a community around your content"
If you view the RSS Feed of dotnetcurry.com over here, you will observe a FeedFlare below each post:
Feed Flare
Let us see how to read this RSS that is powered by FeedFlare.
Step 1: Create a new website (Open VS 2008 > File > New Website) called ‘LINQRSSGridView’.
Step 2: Drag and drop a GridView and a button control to the page.
Step 3: Once you visit the RSS Feed over here, right click on the page and View Source. You will find an XML file, since RSS is an XML file.
A sample portion of the RSS we will be reading, looks similar to the following:
<title xmlns:cf="http://www.microsoft.com/schemas/rss/core/2005" cf:type="text">Display Images From Database In Silverlight 2</title>
<author>Suprotim Agarwal</author><atom:author xmlns:atom="http://www.w3.org/2005/Atom"><atom:name>Suprotim Agarwal</atom:name></atom:author>
 
<description xmlns:cf="http://www.microsoft.com/schemas/rss/core/2005" cf:type="html">In this article, we will see how to display images from database in Silverlight using an ASP.NET HttpHandler. The article will first demonstrate how to do a simple image fetch using an HttpHandler. We will then modify our approach to use WebClient to download images on demand. We will also see how to cancel the image fetch operation midway.
&lt;p&gt;&lt;a href="http://feeds.feedburner.com/~a/netCurryRecentArticles?a=8KZ5s2"&gt;&lt;img src="http://feeds.feedburner.com/~a/netCurryRecentArticles?i=8KZ5s2" border=0&gt;&lt;/a&gt;&lt;/p&gt;&lt;div class=feedflare&gt;
&lt;a href="http://feeds.feedburner.com/~f/netCurryRecentArticles?a=9u3Tm"&gt;&lt;img src="http://feeds.feedburner.com/~f/netCurryRecentArticles?i=9u3Tm" border=0&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/netCurryRecentArticles?a=lYqpM"&gt;&lt;img src="http://feeds.feedburner.com/~f/netCurryRecentArticles?i=lYqpM" border=0&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/netCurryRecentArticles?a=7aL5M"&gt;&lt;img src="http://feeds.feedburner.com/~f/netCurryRecentArticles?i=7aL5M" border=0&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/netCurryRecentArticles?a=8mFFm"&gt;&lt;img src="http://feeds.feedburner.com/~f/netCurryRecentArticles?i=8mFFm" border=0&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/netCurryRecentArticles?a=0shIM"&gt;&lt;img src="http://feeds.feedburner.com/~f/netCurryRecentArticles?i=0shIM" border=0&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/netCurryRecentArticles?a=KqvpM"&gt;&lt;img src="http://feeds.feedburner.com/~f/netCurryRecentArticles?i=KqvpM" border=0&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/netCurryRecentArticles?a=AdTqM"&gt;&lt;img src="http://feeds.feedburner.com/~f/netCurryRecentArticles?i=AdTqM" border=0&gt;&lt;/a&gt;
&lt;/div&gt;</description>
 
<link>http://feeds.feedburner.com/~r/netCurryRecentArticles/~3/431571866/ShowArticle.aspx</link>
 
<pubDate>Sat, 25 Oct 2008 05:12:31 GMT</pubDate>
 
Let us write an LINQ to XML query to read the Title, Link, Description and Author elements from our RSS Feed.
Add the following template Columns to the GridView to display content and the button click event handler:
<form id="form1" runat="server">
<div>   
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Title">
 <ItemTemplate>
 <a href='<%# Eval("link") %>' target="_blank"><%# Eval("title") %></a>
 </ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="description" HtmlEncode="false"
   HeaderText="Description" />
<asp:BoundField DataField="Author"
   HeaderText="Author" />
</Columns>
</asp:GridView>              
    <br />              
</div>
<asp:Button ID="btnFetchRss" runat="server" onclick="btnFetchRss_Click"
    Text="Button" />
</form>
On the click event of the button, add the following code:
C#
protected void btnFetchRss_Click(object sender, EventArgs e)
{
    XElement xFeed = XElement.Load(@"http://feeds.feedburner.com/netCurryRecentArticles");
 
var items =
    from item in xFeed.Elements("channel").Elements("item")
              select new {
                  Title = item.Element("title").Value,
                  Link = item.Element("link").Value,
                  Description = item.Element("description").Value,
                  Author = item.Element("author").Value
              };
 
    GridView1.DataSource = items;
    GridView1.DataBind();
}
VB.NET
    Protected Sub btnFetchRss_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFetchRss.Click
        Dim xFeed As XElement = XElement.Load("http://feeds.feedburner.com/netCurryRecentArticles")
 
        Dim items = _
         From item In xFeed.Elements("channel").Elements("item") _
         Select New With {Key .Title = item.Element("title").Value, _
                          Key .Link = item.Element("link").Value, _
                          Key .Description = item.Element("description").Value, _
                          Key .Author = item.Element("author").Value}
 
        GridView1.DataSource = items
        GridView1.DataBind()
    End Sub
In the code above, we load the Xml from the RSS feed using the XElement class. We then enumerate through all the Channel\Item elements. We then select all the item nodes from this element and bind the results to a GridView.
Observe that I am using C# 3.0/ VB 9.0 features like the ‘Anonymous type’ and ‘Type Inference’. We used an anonymous type here since I wanted to demonstrate how you can cut down on the code required to create and instantiate a class using ‘the old way’. However, if you have to pass the result to a webservice or to a different part of your application, you would need to define a class as shown below. We will call our class ‘ArticlesList’
Note: This particular example shown above works even if we did not create a seperate class, since we are using the results locally and the ‘var’ keyword infers the correct type that the GridView accepts (ie. IEnumerable<anonymoustype>)
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
public class ArticlesList
{
    public string Title { get; set; }
    public string Link { get; set; }
    public string Description { get; set; }
    public string Author { get; set; }
}
 
VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
 
Public Class ArticlesList
 
    Private privateTitle As String
    Public Property Title() As String
        Get
            Return privateTitle
        End Get
        Set(ByVal value As String)
            privateTitle = value
        End Set
    End Property
 
    Private privateLink As String
    Public Property Link() As String
        Get
            Return privateLink
        End Get
        Set(ByVal value As String)
            privateLink = value
        End Set
    End Property
 
    Private privateDescription As String
    Public Property Description() As String
        Get
            Return privateDescription
        End Get
        Set(ByVal value As String)
            privateDescription = value
        End Set
    End Property
 
    Private privateAuthor As String
    Public Property Author() As String
        Get
            Return privateAuthor
        End Get
        Set(ByVal value As String)
            privateAuthor = value
        End Set
    End Property
End Class
Note: C# supports Automatic properties whereas VB.NET does not.
Once we have coded our ArticlesList class, we can then re-write the query to use Generics to return a strongly typed collection of List<ArticlesList> items. This collection can now be passed to any other part of the application.
The re-written query will look similar to the following:
C#
protected void btnFetchRss_Click(object sender, EventArgs e)
{
    XElement xFeed = XElement.Load(@"http://feeds.feedburner.com/netCurryRecentArticles");
 
    IEnumerable<ArticlesList> items =
    from item in xFeed.Elements("channel").Elements("item")
              select new ArticlesList {
                  Title = item.Element("title").Value,
                  Link = item.Element("link").Value,
                  Description = item.Element("description").Value,
                  Author = item.Element("author").Value
              };
 
    GridView1.DataSource = items;
    GridView1.DataBind();
}
VB.NET
    Protected Sub btnFetchRss_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFetchRss.Click
        Dim xFeed As XElement = XElement.Load("http://feeds.feedburner.com/netCurryRecentArticles")
 
        Dim items As IEnumerable(Of ArticlesList) = _
        From item In xFeed.Elements("channel").Elements("item") _
        Select New ArticlesList With {.Title = item.Element("title").Value, _
                         .Link = item.Element("link").Value, _
                         .Description = item.Element("description").Value, _
                         .Author = item.Element("author").Value}
 
        GridView1.DataSource = items
        GridView1.DataBind()
    End Sub
To beautify the GridView, I also added the following CSS in <head>
<head id="Head1" runat="server">
<title>RSS Feed using ASP.NET and LINQ</title>
<style type="text/css">
body
{
font: normal 11px auto "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;   
background-color: #ffffff;
color: #4f6b72;      
}
 
th {
font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
color: #4f6b72;
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
border-top: 1px solid #C1DAD7;
letter-spacing: 2px;
text-transform: uppercase;
text-align: left;
padding: 6px 6px 6px 12px;
background: #D5EDEF;
}
 
td {
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
background: #fff;
padding: 6px 6px 6px 12px;
color: #4f6b72;
}
 
td.alt
{
background: #F5FAFA;
color: #797268;
}
 
td.boldtd
{
font: bold 13px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
background: #D5EDEF;
color: #797268;
}
</style>
 
</head>
On running the application, the results will be displayed in the GridView as shown below:
RSS Malformed
Observe how the tags related to the FeedFlare were not rendered properly and have shown up in a raw format. Now honestly speaking, when I saw this, I was surprised and thought of writing some code that formats the HTML properly.
However I did realize that this issue has got to do something with Encoding. I remembered that the GridView has a property related to HTMLEncoding (BoundField.HtmlEncode). On exploring a bit more, I found this:
"When the HtmlEncode property is true, the value of the field is HTML encoded to its string representation before the formatting string is applied. For some objects, such as dates, you might want to control how the object is displayed with a formatting string. In those cases, you must set the HtmlEncode property to false."
So the solution was quiet simple. Just use ‘HTMLEncode = false’ in the Description bound field.
<asp:BoundField DataField="description" HtmlEncode="false"
               HeaderText="Description" />
On running the application again, the RSS with the FeedFlare looks similar to the following:
RSS LINQ Proper
The RSS Feed Reader is ready. You can expand on this example and use LINQ to XML to choose and filter the XML data in the way you want. I hope this article was useful and I thank you for viewing it
The entire source code of this article in C# and VB.NET can be downloaded from here.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Dennis on Tuesday, December 2, 2008 6:58 PM
Good work!
Comment posted by WebDevVote on Tuesday, December 2, 2008 8:59 PM
this article has been voted!
Track back from http://www.webdevvote.com/AspNet/NET_Reading_RSS_powered_by_FeedFlare_using_ASP_NET_and_LINQ
Comment posted by Fatih on Wednesday, December 3, 2008 3:26 AM
Thx for this great post !
Comment posted by Thanigainathan.S on Thursday, December 4, 2008 3:40 AM
Hi ,

This is really a nice article. Please help me with following questions.
If i want to search through the XML string for a particular values ,i.e if i want to search like a Google RSS search how can we do that here ?

Thanks
Comment posted by Suprotim Agarwal on Friday, December 5, 2008 10:21 AM
Thanigainathan: It would work in a similar manner as shown over here. Instead of the feedburner feed, give the url of the feed you need to search

XElement xFeed = XElement.Load(@"http://feedyouneedtosearch");

var items =
    from item in xFeed.Elements("channel").Elements("item")
              select new {
                  Title = item.Element("title").Value,
                  Link = item.Element("link").Value,
                  Description = item.Element("description").Value
              };

and so on. Since RSS is XML, open the XML and check out the elements.
Comment posted by seenu on Friday, December 5, 2008 4:05 PM
great good article
Comment posted by Navneet on Saturday, December 6, 2008 1:53 AM
Can You Plz tell me how the whole above scenario works for asp.net 2.0.
Comment posted by Navneet on Saturday, December 6, 2008 2:26 AM
Can You Plz tell me how the whole above scenario works for asp.net 2.0.
Comment posted by Navneet on Saturday, December 6, 2008 5:54 AM
Can You Plz tell me how the whole above scenario works for asp.net 2.0.