Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Creating an RSS Feed with ASP.Net in C#

Posted by Ravi Varma Thumati on October 27, 2009

Table of Contents:

  • Creating an RSS Feed with ASP.Net Written in C#
  • Creating the Pages
  • Code behind Page
  • The Data Repeater

Creating an RSS Feed with ASP.Net Written in C#

RSS feeds are massively popular online. It’s no wonder; they’re a great way for users to receive news, blog entries, and other content in which they’re interested. If you want to set one up for your web site, keep reading.

What is RSS?

RSS. Your probably already know what this is, but put simply RSS (Really Simple Syndication) is just an XML file served up by a web server, normally containing news items, stock prices and so forth.

The file contains certain tags that define it as an RSS feed (such as the opening <rss version=”2.0″> tag).

RSS feed readers such Sharp Reader can use these XML files and display their content, headlines and more. These readers mean that, from one place, you can easily see all the news and information to which you have subscribed.

In this article, we will go though creating an RSS feed, using an ASP.Net web page, written in C#. We will also need to have a back end SQL server database that contains the news stories we are going to put into the RSS feed.

Layout of Database table

First of all, we need to have the database with some stories in it. For this article we will be using a table as described in the table below.

Field name Field Type Notes
id Unique integer id of the field ID of the story
headline VarChar field, 75 long Headline of the story
story_text Text field Full text of the story

If you are creating the database from scratch, make sure there is some test data in there to use. The headline field will be what most people first see in the RSS reader application.

Once you have the above table (call it something like tbl_stories), you can start to create the ASP.Net page that will serve the feed.

Creating the Pages

There will be two files in this project. One will contain an ASP.Net repeater control that will put the data into the XML file. The other will be a code behind page that contains all the logic for getting the data. You can create these pages in an IDE like Visual Studio or Visual Web Developer, or just use a plain text editor. If you are using a text editor, you will have to copy the pages onto your IIS server in order to test them.

First of all, create a page called rss.aspx. This is the page that contains the data repeater control, at which your users will actually point their RSS reader applications.

At the very top of the page, you need to have the line shown below. It is the page declaration statement, and tells the page how to behave:

<%@ Page language=”c#” CodeFile=”rss.aspx.cs” ContentType=”text/xml” AutoEventWireup=”false” Inherits=”SyndicationDemo”%>

The first declaration is the language; it tells you what code to expect on this page. It is set to C#.

The next part of this is the CodeFile section. It is telling us the code for the page is located within another file, in this case the rss.aspx.cs file.

The next section is important; it is setting the ContentType of the page. If this were a normal web page you wouldn’t have to change it (it defaults to HTML), but we want to send XML to the browser (or RSS reader), so we make it text/xml.

The Inherits section tells the page what class to inherit from the code behind page. In the case it’s the SyndicationDemo class, which we will be writing next.

We will now create the code behind page. It makes more sense to do this before we add the repeater to this page, so you can see what the repeater is actually outputting.

Code Behind Page

Create a new file called rss.aspx.cs in the same place you have created the rss.aspx page.

At the very top of the page, we will tell the pages about all the dot.net classes we will be using, as follows:

using System;

using System.Text;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Xml;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

After that we create the namespace, and set it to be a web page

namespace SyndicationDemo

{

   //Class for returning RSS feed Data

   public partial class rss : System.Web.UI.Page

   {

Now we will write the page load event. This will run every time someone requests the page. It basically queries our database for the information, and then binds this to the repeater control.

private void Page_Load(object sender, System.EventArgs e)

{

   // Connect to the Database

   SqlConnection myConnection = new SqlConnection(“Data Source=DBServer1;Initial Catalog=rss_news;Persist Security Info=True;User;Password=Pass;”);

   // Retrieve the SQL query results and bind it to the Repeater

   const string SQL_QUERY = “SELECT top 50 id, headline, story_text, FROM news_stories”;

   SqlCommand myCommand = new SqlCommand(SQL_QUERY, myConnection);

   myConnection.Open();

   rptRSS.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

   rptRSS.DataBind();

   myConnection.Close();

}

The first thing we do is create a SQL server connection to our database. In a real world production application you would want to add some exception handling to the code; it is left out here to made the code more readable.

Once we have connected, we run a SQL query on the database to return our stories. The SQL here is using the TOP keyword so we only return a limited number of stories to show. In the real world you might limit this to stories within a certain date, of a certain status, and so on.

The TOP keyword might not work if you are using a database that is hosted on a non-Microsoft SQL server.

We then open the connection to the database, execute the SQL against this connection, bind the SQL queries results to the repeater and close the connections.

The last part of the code behind page is a simple function that will be called from the main page. This function replaces any chars in your stories that are XML reserved characters

protected string FormatForXML(object input)

{

   string data = input.ToString(); //cast input to string

   // replace those characters disallowed in XML documents

   data = data.Replace(“&”, “&amp;”);

   data = data.Replace(“””, “&quot;”);

   data = data.Replace(“‘”, “&apos;”);

   data = data.Replace(“<“, “&lt;”);

   data = data.Replace(“>”, “&gt;”);

   return data;

}

The function just accepts one argument, casts it to a text type and does a find and replace on the reserved characters to make them valid.

Creating an RSS feed for your ASP.NET site

How useful a RSS feed actually is is hard for me to say something about, I personally have a hard time understanding the buzz about blogs (why should that be better than a regular website).

While the content people present in blogs might be really good – I just love Scott Guthries blog, the big problem with blogs (and I mean the actual blog applications) is categorization of data. How fun is it to try t find a specific article – to find you have to browse to the month you believe it was published. While the search engines might have been approved and categorization with Tags is becoming more popular in blog software I still think the actual navigation is pretty lame.

But for news aggregating – fine, I can buy that idea, RSS has been tightly coupled with blogs but there is no reason as to why you couldn’t put up a RSS feed for your (non-blog) site. So, that’s what I have decided to do – and will describe for you here.

First, we are using a ASHX handler – that technique is described in a separate article

Now lets try to fins out what RSS is about. Basically you (the website owner) should return a RSS feed – and that’s simply an XML document following a certain standard, describing new articles on your site.

Lets have a look on a part of my RSS feed:

 <?xml version=”1.0″ encoding=”UTF-8″ ?>

 <rss version=”2.0″>

 <channel>

  <title>ASPCode.net RRS flow</title>

  <link>http://www.aspcode.net/articles/default.aspx</link&gt;

  <description>Articles about ASP.NET, C# and development with Visual Studio</description>

  <ttl>5</ttl>

 <item>

  <title>Creating an RSS feed for your ASP.NET site</title>

  <link>http://www.aspcode.net/articles/l_en-US/t_default/ASP.NET/Creating-an-RSS-feed-for-your-ASP.NET-site_article_277.aspx</link&gt;

  <guid isPermaLink=”true”>http://www.aspcode.net/articles/l_en-US/t_default/ASP.NET/Creating-an-RSS-feed-for-your-ASP.NET-site_article_277.aspx</guid&gt;

  <description>How useful a RSS feed actually is is hard for me to say something about, I personally have a hard time understanding the buzz about blogs (why should that be better than a regular website). While the content people present in blogs might be really good – …</description>

  <pubDate>Wed, 30 Aug 2006 13:00:09 GMT</pubDate>

  </item>

Let’s talk a little about the different tags in the XML file.

title

The name of the channel. It’s how people refer to your service

link

The url to the website

description

Phrase or sentence describing the channel

Ttl

It’s a number of minutes that indicates how long a channel can be cached before refreshing from the source. So, it’s information for the news aggregator/reader program how often it should update it’s content from the feed.

For each item(articles)

title

The header of the article

link

The url of the article

description

Short description – synopsis

guid

A string that uniquely identifies each article. Often you have unique page (url) for each article on your website (for example showart.aspx?id=123) so it’s most often ok to use the link as guid.

pubDate

date when the article was published, ex format Sat, 07 Sep 2002 00:00:01 GMT

This was just a brief overview of what tags you might want to use in your RSS feed, for an extensive explaination, please go to RSS 2.0 Specification

So that’s what we are gonna create – when people/programs(news aggregators) access the page rss.ashx the document should be returned as an XML file.

All action takes place in the handlers ProcessRequest

public void ProcessRequest (HttpContext context)

{

            string sTxt = BuildXmlString();

            context.Response.ContentType = “text/xml”;

            context.Response.ContentEncoding = System.Text.Encoding.UTF8;

 

            context.Response.Write( sTxt );

  }

Well, maybe not so much action there, the building of the XML is done in BuildXmlString 

private string BuildXmlString()

{

    string sTitle = “The title if your blog”;

    string sSiteUrl = “http://www.aspcode.net&#8221;;

    string sDescription = “The site is the coolest bla bla and this rss feed is the best!”;

    string sTTL = “60”;

 

    System.Text.StringBuilder oBuilder = new System.Text.StringBuilder();

    oBuilder.Append(“<?xml version=\”1.0\” encoding=\”UTF-8\”?>”);

    oBuilder.Append(“<rss version=\”2.0\”><channel>”);

 

    oBuilder.Append(“<title>”);

    oBuilder.Append(sTitle);

    oBuilder.Append(“</title>”);

 

    oBuilder.Append(“<link>”);

    oBuilder.Append(sSiteUrl);

    oBuilder.Append(“</link>”);

 

    oBuilder.Append(“<description>”);

    oBuilder.Append(sDescription);

    oBuilder.Append(“</description>”);

    oBuilder.Append(“<ttl>”);

    oBuilder.Append(sTTL);

    oBuilder.Append(“</ttl>”);

    AppendItems(oBuilder);

    oBuilder.Append(“</channel></rss>”);

    return oBuilder.ToString();

}

This builds up the basic structure of the document, with title, description, ttl etc and now we are going to add the actual articles – that’s what happens in AppendItems 

public void AppendItems(System.Text.StringBuilder oBuilder)

{

    //read from database or whatever and retrieve the 10 latest articles

    //I have a class, ObjClasses.Article and a collection

    //ObjClasses.ArticleList which does the retrieving

    ObjClasses.ArticleList oList = new ObjClasses.ArticleList();

    oList.OpenLatest(10);

    foreach( ObjClasses.Article oArt in oList )

    {

        string sTitle = oArt.Header;

        string sLink = “http://www.aspcode.net/wharver/showarticle.aspx?id=&#8221; + oArtId.ToString() ;

        string sDescription = oArt.ShortDescr;

        string sPubDate = oArt.LastModified.ToString(“R”);

        oBuilder.Append(“<item>”);

 

        oBuilder.Append(“<title>”);

        oBuilder.Append(  sTitle);

        oBuilder.Append(“</title>”);

        oBuilder.Append(“<link>”);

        oBuilder.Append(sLink);

        oBuilder.Append(“</link>”);

        oBuilder.Append(“<guid isPermaLink=\”true\”>”);

        oBuilder.Append(sLink);

        oBuilder.Append(“</guid>”);

        oBuilder.Append(“<description>”);

        oBuilder.Append(sDescription);

        oBuilder.Append(“</description>”);

        oBuilder.Append(“<pubDate>”);

        oBuilder.Append(sPubDate);

        oBuilder.Append(“</pubDate>”);

        oBuilder.Append(“</item>”);

    }

}

This is everything, actually. I will still make one improvement – caching:

public void ProcessRequest (HttpContext context)

{  

            string sTxt = “”;

            if ( context.Cache[“RSSFEED123”] == null )

            {

                        sTxt = BuildXmlString(context);

                        context.Cache.Insert( “RSSFEED123”, sTxt );

            }

            else

                        sTxt = context.Cache[“RSSFEED123”].ToString();

 

            context.Response.ContentType = “text/xml”;

            context.Response.ContentEncoding = System.Text.Encoding.UTF8;

            context.Response.Write( sTxt );

}

You might spot the potential problem here – the cached string lives forever (until the webapplication restarts actually) but you can of course insert your string with a CacheDependency – or do as I do – please read the related article about ASP.NET caching control

Added: 2006-09-20

I use pretty much this exact script on this very site but after a while I found that the rss feed generated was corrupt. It turned out that I had added some articles with quotes etc and it of course broke the xml.The fix is to add CDATA sections:

oBuilder.Append(“<item>”);

oBuilder.Append(“<title><![CDATA[ “);

oBuilder.Append(  sTitle);

oBuilder.Append(” ]]> </title>”);

oBuilder.Append(“<link>”);

oBuilder.Append(sLink);

oBuilder.Append(“</link>”);

oBuilder.Append(“<guid isPermaLink=\”true\”>”);

oBuilder.Append(sLink);

oBuilder.Append(“</guid>”);

oBuilder.Append(“<description><![CDATA[ “);

oBuilder.Append(sDescription);

oBuilder.Append(” ]]> </description>”);

oBuilder.Append(“<pubDate>”);

oBuilder.Append(sPubDate);

oBuilder.Append(“</pubDate>”);

oBuilder.Append(“</item>”);

 

Advertisements

2 Responses to “Creating an RSS Feed with ASP.Net in C#”

  1. Thank you for the good writeup. It actually was a entertainment account it. Look advanced to far added agreeable from you! By the way, how can we communicate?

  2. Raul Munoz said

    I really enjoyed your post, thanks for sharing. — Raul Munoz

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: