C# RSS Builder : How to Build Really Simple Syndications



RSS has become quite popular recently, and from developer's point of view, it's a quite common requirement to implement. So I have decided to make an object-oriented approach and write a few classes that might come in handy. You can see the source code below, it is quite simple and straightforward. One note to those who haven't read my previous posts: The retrieval from the database is made by another set of classes called DatabaseEntities. These classes allow me to directly bind C# classes with SQL table columns and return lists of business objects instead of DataTables.
Back to the RSS feed, there are a few things you need to do: first you need RSS items, as by the standard of the RSS XML tags. Then you need to create a logo of the RSS feed. This is optional, but it is a nice way to offer your readers visual connection to your brand. You will also need a Stream object where the feed should be output. It could be any type of stream. For the purposes of this example, I am using a FileStream, but for a real scenario (ASP.NET) you would need to use the Response's output stream. Take a look at the code, and please tell me if it is REALLY SIMPLE :)



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RssBuilderLibrary;
using System.IO;
using DataBaseClassLibrary;
using System.Data;
namespace RssBuilderLibraryClient
{
class Program
{
static void Main(string[] args)
{
    /* Retrieve the latest products from the database as RSS items */
    string ConnectionString = "...";
    GenericDbEntity<RssItem> dbEntity = new GenericDbEntity<RssItem>("GetLatestProducts", 
ConnectionString);
    List<RssItem> latestProducts = (List<RssItem>) dbEntity.Select();
    
    /* Create an image logo in the RSS feed */
    RssImage imageLogo = new RssImage();
    imageLogo.Description = "This is a description";
    imageLogo.Title = "This is a title";
    imageLogo.Url = "http://example.com/image.jpg";
    imageLogo.Link = "http://mysite.com";

    /* Create a stream where the feed should be output - it could be any type of stream */
    FileStream fileStream = File.Create("rssfeed.xml");

    /* Create a RSS channel */
    RssChannel rss = new RssChannel(fileStream, imageLogo);

    /* Add all RSS items in the channel */
    foreach(IRssItem rssItem in latestProducts)
    {
        rss.AddRssItem(rssItem);
    }

    /* Publish the RSS feed to the output stream */
    rss.Publish();
}
}
}

No comments:

Post a Comment