ControlFreak
LANGUAGES:VB.NET | C#
ASP.NETVERSIONS: 2.x
Feed RSS to Your Users
Create RSS Feeds for Users to Consume on Their Terms
By Steve C. Orr
When you publish a new item on your Web site you usually mustwait for users to visit it in order for them to discover the new item. And there?sno telling when that will be. Even if your users would be genuinely excitedabout the new item, they simply don?t know about it yet. Some Web sites sendout e-mail newsletters to inform users of developing news, but, for a varietyof reasons, this is often less than ideal: overzealous spam filters,overwhelmed inboxes, and information overload can cause users to overlook suchan information source. Users get annoyed by e-mail newsletters that come toooften, and newsletters that come too infrequently could cause users to loseinterest in your site. What?s really needed is a technology that puts users inthe driver?s seat. Most users have limited time and, therefore, prefer a quickand consolidated summary of what?s new and noteworthy on your site and others. That?swhere RSS comes in ...
What Is RSS?
Really Simple Syndication (RSS) is an XML-based formatthat provides a simple way to let users know about new news stories in a waythat?s convenient to them. There is a virtually infinite supply of RSS feedsavailable on the Internet. When a user visits an interesting Web site and seesa symbol similar to Figure 1, it?s an indication that an RSS feed is availableto which they may want to subscribe.
Figure 1: This little symbolindicates to users that the Web site they are viewing has an RSS feed availableso they can easily keep up to date on breaking news stories from that site.
There is a variety of software available on the Internetthat lets users subscribe to and consume RSS feeds in a fashion that?sconvenient to them. Such news aggregators keep track of which stories usershave already read, and generally highlight new news stories that may be ofinterest. While there are software programs available that are dedicated solelyto RSS reading and aggregation, RSS support is also built into most current Webbrowsers. Internet Explorer 7 should be released by the time you read this, andit has fantastic new RSS support built in (see Figure 2). Firefox 1.5 haslimited RSS support built in, as well.
Figure 2: Internet Explorer 7 hasexcellent new built-in RSS reading capabilities, including friendlysubscription features, attractive RSS formatting, and powerful filteringcapabilities.
RSS Format
For your Web site to provide RSS support, it must simplyprovide an XML file in a specific format that summarizes the news articles youwish to publicize. While the XML format for RSS has a long and controversialhistory, RSS 2.0 is the format I recommend, because it is simple and widelysupported. A sample of this format is shown in Figure 3.
<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0">
<channel>
<title>Toothpasteand Ammunition web site</title>
<link>http://www.T&A.net</link>
<description>Newsabout Toothpaste and Ammo</description>
<language>en-US</language>
<webMaster>BarryBigalow@T&A.net</webMaster>
<item>
<title>ColgateSupreme prevents tooth decay</title>
<description>Preventingtooth decay</description>
<link>http://www.T&A.net/decay.aspx</link>
<author>MaryBigalow@T&A.net</author>
<category>Toothpaste</category>
<pubDate>Fri, 15 Jan 2007 03:47:37 GMT</pubDate>
</item>
<item>
<title>.44caliber special</title>
<description>Bigammo sale</description>
<link>http://www.T&A.net/sale.aspx</link>
<author>TerryBigalow@T&A.net</author>
<category>Ammo</category>
<pubDate>Sat, 16 Jan 2007 04:48:21 GMT</pubDate>
</item>
</channel>
</rss>
Figure 3: This XMLsample shows the RSS 2.0 format, which is simple and widely supported.
An RSS feed contains a channel element, which contains therequired sub elements title, link, and description. The channel can alsocontain other optional sub elements, such as language, webMaster, and others. Figure4 contains a list of the channel element?s required elements, along with manyof its more popular optional elements. For a complete list, see the RSS 2.0specification at http://validator.w3.org/feed/docs/rss2.html.
| Channel Elements | Description of the Element?s Value |
| title | (Required) The name of the channel as it should appear to end users. |
| description | (Required) A brief narrative about the contents of the channel. |
| link | (Required) The URL that leads to the Web site that corresponds with this channel. |
| language | (Optional) Standard language code of the main language of the Web site. |
| webMaster | (Optional) The e-mail address of the Web site?s Webmaster. |
| lastBuildDate | (Optional) The time and date that the channel contents last changed. |
| ttl | (Optional) ?Time To Live? ? The number of minutes that the channel can be cached. |
Figure 4: Theseare some of the most useful channel elements defined by the RSS 2.0 XMLstandard.
The channel element also contains a series of Items, whicheach also contain the required sub elements title, link, and description. Ittoo can contain a variety of optional elements, such as the category andpubDate elements shown in this example. Figure 5 contains a list of all the requiredand optional item sub elements.
| Item Elements | Description of the Element?s Value |
| title | (Required) The name of the item as it should appear to end users. |
| description | (Required) A brief narrative about the contents of the item. |
| link | (Required) The URL that leads to the full article. |
| author | (Optional) The e-mail address of the item?s author. |
| category | (Optional) The name of the category to which the item belongs. |
| comments | (Optional) A URL to a page that has comments about the item. |
| enclosure | (Optional) The URL to a media file about the item (such as a hyperlink to an MP3 or video file). |
| guid | (Optional) A string that uniquely identifies the item. |
| pubDate | (Optional) The date and time that the item was published. |
| source | (Optional) The RSS channel from which the item originally came. |
Figure 5: This isthe complete list of sub elements supported by the item element according tothe RSS 2.0 XML standard.
SiteMap Files
Many ASP.NET 2.0 Web applications already have an XMLdocument that describes the pages that comprise the site. ASP.NET 2.0 SiteMapshave a structure not entirely dissimilar to the RSS 2.0 standard. All it takesis a little code to translate a SiteMap into the RSS 2.0 structure. Figure 6shows a sample of a basic SiteMap file.
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com..." >
<siteMapNodeurl="" title="Top" description="Top">
<siteMapNodeurl=""
title="Software"
description="Software">
<siteMapNode url="~\default4.aspx"
title="Financial"
description="Financial"/>
<siteMapNode url="~\default5.aspx"
title="OfficeSuites"
description="Office Suites" />
</siteMapNode>
<siteMapNodeurl=""
title="Hardware"
description="Hardware">
<siteMapNode url="~\default8.aspx"
title="Computers"
description="Computers" />
<siteMapNode url="~\default9.aspx"
title="Keyboards"
description="Keyboards" />
</siteMapNode>
<siteMapNode url=""
title="Books"
description="Books">
<siteMapNode url="~\defaultb.aspx"
title="Fiction"
description="Fiction" />
<siteMapNode url="~\default.aspx"
title="Finances"
description="Finances"/>
</siteMapNode>
</siteMapNode>
</siteMap>
Figure 6: ASP.NET2.0 SiteMap files are comprised of a format that is not entirely dissimilar tothe RSS 2.0 XML standard, which makes it easy to translate from one format tothe other.
As you can see, each SiteMap file contains title,description, and url attributes ? very similar to the item elements in an RSS2.0 file. SiteMap files can be very useful for binding to menus and othernavigational controls, and with a little effort they can also be quite usefulfor RSS feed generation. For more details about SiteMap files, see AutomateNavigation Chores.
Generating an RSS Feed from a SiteMap File
The RSS.aspx.vb file shown in Figure 7 consumes a standardtwo-level SiteMap file (as shown in Figure 6) and generates an XML RSS feedfrom it.
Imports System.Xml
Partial Class RSS
InheritsSystem.Web.UI.Page
Protected SubPage_Load(ByVal sender As Object, _
ByVal e AsSystem.EventArgs) Handles Me.Load
'Clear the response andprepare it for Xml output
Response.Clear()
Response.ContentType= "text/xml"
Response.AddHeader("Content-Disposition", _
"inline;filename=rss.xml")
'Instantiate an Xml TextWriter object
Dim xtw AsXmlTextWriter = _
NewXmlTextWriter(Response.OutputStream, _
Encoding.UTF8)
xtw.WriteStartDocument()
'Required RSS tags
xtw.WriteStartElement("rss")
xtw.WriteAttributeString("version", "2.0")
'Create Channel Tags
xtw.WriteStartElement("channel")
xtw.WriteElementString("title", "Some Web Site")
xtw.WriteElementString("link", "http://SomeWeb.net")
xtw.WriteElementString("description", "Techie Stuff")
xtw.WriteElementString("language", "en-US")
'Output each item
For Each smnTop AsSiteMapNode _
InSiteMap.RootNode.ChildNodes
For Each smn AsSiteMapNode In smnTop.ChildNodes
xtw.WriteStartElement("item")
xtw.WriteElementString("title",smn.Title)
xtw.WriteElementString("description", _
smn.Description)
xtw.WriteElementString("category", smnTop.Title)
'Generate the item's URL
Dim baseUri AsNew Uri("http://SomeWeb.net")
Dim myUri As NewUri(baseUri, smn.Url)
xtw.WriteElementString("link", myUri.AbsoluteUri)
'Close the item tag
xtw.WriteEndElement()
Next
Next
'Close each remainingtag
xtw.WriteEndElement()
xtw.WriteEndElement()
xtw.WriteEndDocument()
xtw.Flush()
xtw.Close()
Response.End()
End Sub
End Class
Figure 7: ThisASPX page processes the Web application?s SiteMap file and generates an RSSfeed from it.
The page starts by clearing the Response object because wedon?t want any of the usual HTML headers to be output since the goal is tooutput an XML file. The next two lines in the first code block also aim to makeit clear to the browser that this is to be interpreted as an XML document, nota Web page.
The second code block of Figure 7 instantiates an Xml TextWriter object so that it can later be filled with the resulting RSS formatted XML.The third code block outputs the initial XML element, which identifies it as anRSS 2.0 formatted XML file.
The fourth code block of Figure 7 creates the Channelelement and all of its sub elements (except the Item list), These sub elementsspecify the title of the channel, the URL that the channel represents, a descriptionof the channel, and the language in which it is published.
The main loop in Figure 7 outputs each item in the two-levelhierarchy of the SiteMap shown in Figure 6. Each Item has a title, description,category, and link sub element. A few lines of code are needed to calculate theitem?s absolute URL, because relative paths are not very useful in an RSS feed.
Finally, each XML element tag is closed. The resulting RSSdocument is shown in Figure 8, which can be consumed by any standard RSS-readingsoftware, including Internet Explorer 7.
<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0">
<channel>
<title>Some WebSite</title>
<link>http://SomeWeb.net</link>
<description>ComputerStuff</description>
<language>en-US</language>
<item>
<title>Financial</title>
<description>Financial</description>
<category>Software</category>
<link>http://someweb.net/RSS/default4.aspx</link>
</item>
<item>
<title>OfficeSuites</title>
<description>OfficeSuites</description>
<category>Software</category>
<link>http://someweb.net/RSS/default5.aspx</link>
</item>
<item>
<title>Computers</title>
<description>Computers</description>
<category>Hardware</category>
<link>http://someweb.net/RSS/default8.aspx</link>
</item>
<item>
<title>Keyboards</title>
<description>Keyboards</description>
<category>Hardware</category>
<link>http://someweb.net/RSS/default9.aspx</link>
</item>
<item>
<title>Fiction</title>
<description>Fiction</description>
<category>Books</category>
<link>http://someweb.net/RSS/defaultb.aspx</link>
</item>
<item>
<title>Finances</title>
<description>Finances</description>
<category>Books</category>
<link>http://someweb.net/RSS/default.aspx</link>
</item>
</channel>
</rss>
Figure 8: This RSSis the result of processing the SiteMap in Figure 6 through the code of Figure7.
Adding Internet Explorer 7 and Firefox Support
As mentioned earlier, Internet Explorer 7 has exciting newsupport for RSS (as shown in Figure 2). It has user-friendly subscription features,attractive formatting of otherwise ugly XML, and powerful filtering and sortingcapabilities so users can right away get to the stories in which they?reinterested.
However, for Internet Explorer 7 and Firefox to providetheir RSS support, they must first be informed that your Web site has a relatedRSS feed available. It only takes a single link element in the header sectionof a Web page to ensure these browsers recognize the RSS file for your site:
<head runat="server">
<linkrel="alternate"
type="application/rss+xml"
title="Some WebSite's RSS Feed"
href="http://someweb.net/rss.aspx" />
</head>
The href attribute needs to point to your RSS file. In theprevious examples, the RSS is dynamically generated by an ASPX page, but you couldjust as easily point the above href attribute to a manually maintained (orperiodically generated) static XML file.
When this link element is present the browser will lightup the icon pictured in Figure 1, drawing attention to the feed and enabling advancedfeed-handling functionality.
I suggest you put such a link element into your masterpage so Internet Explorer 7 recognizes the RSS feed is associated with all Webpages within your site. Of course, more complex scenarios are possible, such ashaving more than one RSS feed available (or more than one channel) andassociating them with specific pages, but I?ll leave this as an exercise foryou.
Conclusion
RSS has long been an effective way to ensure new newsitems are published in a timely manner that allows users to stay informednon-intrusively. Now that major browsers are adding deluxe support for RSS, itcan no longer go ignored by the masses. Soon your users will be demanding RSSfeeds, so it is time to become familiar with them so you can give users thesolutions they seek.
The sample code forthis article is available for download (in both VB.NET and C#).
Steve C. Orr is anMCSD and a Microsoft MVP in ASP.NET. He?s been developing software solutionsfor leading companies in the Seattlearea for more than a decade. When he?s not busy designing software systems orwriting about them, he can often be found loitering at local user groups andhabitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.netor e-mail him at mailto:Steve@Orr.net.