You
already have all the pieces you need to actually create the feed: It’s
merely an XML file, after all. The more important question is this:
When do you generate it?
There are a few options:
Each time content is created or updated.
On a regular schedule (once an hour, for example).
On each request (possibly with caching).
An example of the last option is to create a custom handler for IIS.
In a class library project, define this class:
class RssGenerator : System.Web.IHttpHandler
{
RssLib.Feed feed = new RssLib.Feed();
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(System.Web.HttpContext context)
{
context.Response.ContentType = "application/xml";
CreateFeedContent(context.Response.OutputStream);
}
#endregion
private void CreateFeedContent(Stream outStream)
{
RssLib.Channel channel = GetFeedFromDB();
feed.Write(outStream, channel);
}
private RssLib.Channel GetFeedFromDB()
{
using (IDataReader reader = CreateDataSet().CreateDataReader())
{
RssLib.Channel channel = new RssLib.Channel();
channel.Title = "Test Feed";
channel.Link = "http://localhost";
channel.Description = "A sample RSS generator";
channel.Culture = CultureInfo.CurrentCulture;
channel.Items = new List<RssLib.Item>();
while (reader.Read())
{
RssLib.Item item = new RssLib.Item();
item.Title = reader["title"] as string;
item.Link = reader["link"] as string;
item.PubDate = reader["pubDate"] as string;
item.Description = reader["description"] as string;
channel.Items.Add(item);
}
return channel;
}
}
private static DataSet CreateDataSet()
{
DataSet dataSet = new DataSet();
//get results from database and populate DataSet
return dataSet;
}
}
To use this in a web project, you must modify the web project’s web.config to reference it:
<httpHandlers>
...
<!-- type="Namespace.ClassName,AssemblyName" -->
<add verb="GET" path="feed.xml"
type="IISRssHandler.RssGenerator,IISRssHandler"/>
</httpHandlers>
Now,
whenever you access the project’s feed.xml file via a web browser, the
handler will intercept the request and run your code to generate the
RSS.
Note
Rather
than generate the results on each request, you may want to implement a
simple caching system—only generate if the results haven’t been
generated in the last 10 minutes or so; otherwise, use the previous
results.