The problem
Really Simple Syndication (RSS) is a lightweight XML format designed for sharing headlines and other web content. It�s becoming more and more popular due to its simplicity and standardization. There are many RSS web controls already available in the market that are really good and comprehensive. But many of them output the feed in the form of a grid or table.
The solution
So why create another RSS web control? Well, what if we wanted to have a greater degree of control over the output and the display of the feed and didn't want to show the feed in a table or a grid? I also felt that the controls that are out there are far too complicated for such a simple problem. The control is derived from the Repeater
and will expose an ItemCount
property, which will put a limitation on the items displayed.
The RSSFeeder class
The majority of the functionality lies within the DataSource
property. By overriding the default behaviour of the repeater DataSource
property, we can allow the assignment of a RSS feed URL:
public override object DataSource
{
get{return base.DataSource;}
set
{
if(value is string)
{
try
{
XmlTextReader xtr = new XmlTextReader(value.ToString());
DataSet ds = new DataSet();
ds.ReadXml(xtr);
xtr.Close();
base.DataSource = ds.Tables[3];
}
catch
{
throw new ArgumentException("Url must be a valid rss feed.");
}
}
else
base.DataSource = value;
}
}
As you can see from the above code, while setting the DataSource
property, we first check whether it�s a string
, if so, we assume that this is a URL to a RSS feed. We wrap this up in a try
-catch
just in case it isn�t a URL or a valid RSS feed. If the DataSource
isn�t a string
, then we just assign as usual. We use the XmlTextReader
class to read the XML string and load into a DataSet
. We then assign the third table to the DataSource
.
In addition, in the DataSource
we also override the OnItemDataBound
event. This allows us to count and restrict the items displayed:
protected override void OnItemDataBound(RepeaterItemEventArgs e)
{
if(itemCount != 0 && i > itemCount)
e.Item.Visible = false;
i++;
base.OnItemDataBound(e);
}
We first check whether the ItemCount
property has been set and then check if the variable i
hasn�t exceeded it. When i
exceeds the ItemCount
it hides all the other items in the feed.
Conclusion
This control is very simple but effective. Utilizing the flexibility of the repeater control and the natural encapsulation of a custom web control makes this a perfect all round RSS visualiser.
Links and resources