| Publishing And Reading RSS Feeds In ASP.NETWhat Is RSS?RSS or Really Simple Syndication
(version 2.0) is a method of publishing and displaying almost any type of data over
the internet. The most well-known RSS feeds are news and weather related ones provided
by publishers like BBC, Yahoo News, Telegraph India, etc. RSS publishing is not
only related to news, anyone can publish data from a persistent database as he or
she generates the output in the XML format supported and understood by RSS protocol. These feeds are specially useful when people want to display information on their
websites which are maintained and updated regularly by a third party agency. This
saves time and effort in collecting and maintaining the same data all over again. RSS feeds have their outputs as XML formats with specific tags like 
            <channel/>, <title/>,
        <link/>, <description/>,
        etc. While reading the RSS feeds, the subscriber must be aware of the structure
        of the feed. A sample RSS feed is as follows which may be published over the internet
        for some subscriber to access. <rss version="2.0"><channel>
 <title>Employee Details</title>
 <link>http://localhost/RSSFeeds</link>
 <description>Details of all Company Employees...</description>
 <copyright>Copyright 2008 - 2010</copyright>
 <item>
 <title>John
            Doe</title>
 <description>Main
            Street</description>
 <link>http://localhost/RSSFeeds/EmployeeDetails.aspx?EmpId=1</link>
 <pubDate>9/22/2008
            1:43:48 PM</pubDate>
 </item>
 <item>
 <title>Jane
            Doe</title>
 <description>First
            Street</description>
 <link>http://localhost/RSSFeeds/EmployeeDetails.aspx?EmpId=2</link>
 <pubDate>9/22/2008
            1:43:48 PM</pubDate>
 </item>
 <item>
 <title>Andrew
            Doe</title>
 <description>Downtown</description>
 <link>http://localhost/RSSFeeds/EmployeeDetails.aspx?EmpId=3</link>
 <pubDate>9/22/2008
            1:43:48 PM</pubDate>
 </item>
 </channel>
 </rss>
 Available RSS ReadersInstead of developing a custom RSS Reader, you can use a number of readers already
   available on the internet. Some of these are SharpReader, BitsCast, BlogBridge,
   NewsGator, NetNewsWire, Mozilla, FeedDemon, RssBandit, Shrook, Feedreader, etc. RSS feed publishingThis sample application is about publishing SQL Server
2005 table data as a custom RSS feed over the internet. SQL Server 2005 DatabaseTo begin with, let us create a database in SQL Server 2005 with name 
RSSDB. In RSSDB, create a table with name tblEmployees,
having the design as shown in Figure I.
 
 Provide default as 0 to the Emp_IsDeleted column.
  
Image 1. Design of Employee tableEnter some data into the tblEmployees table
as follows:  
Image 2. Employee table filled with some dataSQL Server 2005 Stored Procedure Create a new SQL Server stored procedure called GetEmployees.
 To do this, open a SQL Server 2005 query window, then paste and execute the following: CREATE PROCEDURE [dbo].[GetEmployees]AS
 BEGIN
 SELECT * FROM
tblEmployees
 END
 
 
 ASP.NET 2.0 
Open Microsoft Visual Studio 2005 and create a 'Web Site' with name 
 RSSFeeds. After the project is created, right click on the project node and
 click on 'Add New Item'.In the 'Add New Item' dialog box, select 'Web Form' and enter the name EmployeeDetails.aspx in the 'Name' area and click
 on Add.Create a new web.config file and inside the
 <configuration></configuration>
 section enter the following: <connectionStrings><add
 name="SQLEmployee"
 connectionString="Data
 Source={server name};DataBase=RSSDB;User Id=JavaUser; Password=*****;"/>
 </connectionStrings>
Open the 'Source' view of EmployeeDetails.aspx.After the first line of <%@ Page %>
 directive, add the following:      <%@ OutputCache 
Duration="120"
%>  While creating a dynamic RSS feed, a problem may creep in while the user provides
 different parameter names like, EmpId to the
 RSS feed url. It may happen that when the user tries to view the output with a different
 EmpId, the output that is shown is the old one.
 It happens as the previous cached page is retrieved. To work around this problem,
 VaryByParam is used to tell the cache that the
 output varies based on this parameter value (EmpId)
 and a new cache needs to be created based on the EmpId
 value passed. In that case, instead of the previous statement, include the line
 as follows: <%@ 
 OutputCache Duration="120"
 VaryByParam="EmpId"
 %>  
 Open the EmployeeDetails.aspx.cs page.Inside the Page_Load function, enter the following block:      if (!Page.IsPostBack){}
 
 Inside the Page.IsPostBack block, enter the
 following lines of code:      // Clear the response
 buffer contentsResponse.Clear();
 Response.ContentType = "text/xml";
 XmlTextWriter xmlRSSFeed = new XmlTextWriter(Response.OutputStream,
 Encoding.UTF8);
 
 // Start writing the rss
 tags
 xmlRSSFeed.WriteStartDocument();
 xmlRSSFeed.WriteStartElement("rss");
 xmlRSSFeed.WriteAttributeString("version",
 "2.0");
 xmlRSSFeed.WriteStartElement("channel");
 xmlRSSFeed.WriteElementString("title",
 "Employee Details");
 xmlRSSFeed.WriteElementString("link",
 "http://localhost/RSSFeeds");
 xmlRSSFeed.WriteElementString("description",
 "Details of all Company Employees...");
 xmlRSSFeed.WriteElementString("copyright",
 "Copyright 2008 - 2010");
 
 // Objects needed for connecting
 to the SQL database
 SqlConnection sqlCon;
 SqlCommand sqlCmd;
 SqlDataReader sqlDr;
 
 // Call SQL Server stored
 procedure
 sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLEmployee"].ToString());
 sqlCmd = new SqlCommand("GetEmployees",
 sqlCon);
 sqlCmd.CommandType = CommandType.StoredProcedure;
 
 sqlCon.Open();
 
 sqlDr = sqlCmd.ExecuteReader();
 
 // Loop through the content
 of the database and add them to the RSS feed
 while (sqlDr.Read())
 {
 xmlRSSFeed.WriteStartElement("item");
 xmlRSSFeed.WriteElementString("title", sqlDr["Emp_FirstName"].ToString()
 + " " +
 sqlDr["Emp_LastName"].ToString());
 xmlRSSFeed.WriteElementString("description", sqlDr["Emp_Address"].ToString());
 xmlRSSFeed.WriteElementString("link", "http://localhost/RSSFeeds/EmployeeDetails.aspx?EmpID="
 +
 sqlDr["Emp_Id"]);
 xmlRSSFeed.WriteElementString("pubDate", DateTime.Now.ToString());
 xmlRSSFeed.WriteEndElement();
 
 }
 sqlDr.Close();
 sqlCon.Close();
 
 // Close all tags
 xmlRSSFeed.WriteEndElement();
 xmlRSSFeed.WriteEndElement();
 xmlRSSFeed.WriteEndDocument();
 xmlRSSFeed.Flush();
 xmlRSSFeed.Close();
 Response.End();
 
 
 Right-click EmployeeDetails.aspx and click on
 'Set as Start Page'.Run the project from inside Visual Studio 2005. RSS feed readerA custom RSS Feed Reader can be developed in ASP.NET 2.0 targeting the feed: http://localhost/RSSFeeds/EmployeeDetails.aspx ASP.NET 2.0 
 Open Microsoft Visual Studio 2005 and create a 'Web Site' with name 
 RSSFeedReader. After the project is created, right click on the project node
 and click on 'Add New Item'.In the 'Add New Item' dialog box, select 'Web Form' and enter the name RSSRead.aspx in the 'Name' area and click on Add.Open the 'Source' view of 
 RSSRead.aspx.Inside the <form> tag of RSSRead.aspx
 document, include the following html:       <table cellpadding="0" cellspacing="0"><tr>
 <td>
 <table class="NormalText" runat="server" id="tblNews" cellpadding="0" cellspacing="0">
 </table>
 </td>
 </tr>
 </table>
 
 Open RSSRead.aspx.cs.Include the following
  using statements at the top of the file:
  using System.Net;using System.Xml;
 using System.IO;
Create a method as follows inside the document:      public void
 ProcessRSSItem(string rssURL){
 //
 Read the RSS feed
 WebRequest
 myRequest = WebRequest.Create(rssURL);
 WebResponse
 myResponse = myRequest.GetResponse();
 
 Stream
 rssStream = myResponse.GetResponseStream();
 
 //
 Load a XML Document
 XmlDocument
 rssDoc = new XmlDocument();
 rssDoc.Load(rssStream);
 
 XmlNodeList
 rssItems = rssDoc.SelectNodes("rss/channel/item");
 
 string
 title = "";
 string
 link = "";
 string
 description = "";
 
 //
 Loop through RSS Feed items
 for
 (int i = 0; i < rssItems.Count; i++)
 {
 XmlNode rssDetail;
 
 rssDetail
 = rssItems.Item(i).SelectSingleNode("title");
 if (rssDetail != null)
 {
 title
 = rssDetail.InnerText;
 }
 else
 {
 title
 = "";
 }
 
 rssDetail = rssItems.Item(i).SelectSingleNode("link");
 if
 (rssDetail != null)
 {
 link
 = rssDetail.InnerText;
 }
 else
 {
 link
 = "";
 }
 
 rssDetail = rssItems.Item(i).SelectSingleNode("description");
 if (rssDetail != null)
 {
 description
 = rssDetail.InnerText;
 }
 else
 {
 description
 = "";
 }
 
 //
 Populate the HTML table rows and cells
 HtmlTableCell
 cell1 = new HtmlTableCell();
 cell1.InnerHtml = "<b><a
 href='" + link + "' target='new'>"
 + title + "</a></b>";
 HtmlTableRow
 tr1 = new HtmlTableRow();
 tr1.Cells.Add(cell1);
 tblNews.Rows.Add(tr1);
 HtmlTableCell
 cell2 = new HtmlTableCell();
 cell2.InnerHtml = "<p
 align='justify'>" + description + "</p>";
 HtmlTableRow
 tr2 = new HtmlTableRow();
 tr2.Cells.Add(cell2);
 tblNews.Rows.Add(tr2);
 }
 }
 
 Inside the Page_Load method, write the following
  code to call the ProcessRSSItem method:      string rssURL
 = "http://localhost/RSSFeeds/EmployeeDetails.aspx".ToString();try
 {
 ProcessRSSItem(rssURL);
 }
 catch (Exception
 ex)
 {
 }
 
 Right-click RSSRead.aspx and click on 'Set as
 Start Page'.Run the project from inside Visual Studio 2005 and enjoy new feature. Happy Programming! 
 Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |    
 |