Sunday, May 31, 2009

RSS Viewer webpart

Scenario:
RSS Viewer webpart for WSS

Code:

using System;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;

namespace TrainingSKN
{
public class RSSWebpart : System.Web.UI.WebControls.WebParts.WebPart
{
Table table;

private string rssUrl;
[Personalizable(true)]
[WebBrowsable()]
public virtual string RssUrl
{
get { return rssUrl; }
set { rssUrl = value; }
}
protected virtual void AddContainer()
{
table = new Table();
table.CellSpacing = 5;
Controls.Add(table);
}
protected virtual void AddItemToContainer(XmlReader reader)
{
string link = string.Empty; ;
string title = string.Empty;
string description = string.Empty;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "link")
link = reader.ReadElementContentAsString();
else if (reader.Name == "title")
title = reader.ReadElementContentAsString();
else if (reader.Name == "description")
description = reader.ReadElementContentAsString();
}
}
TableRow row = new TableRow();
table.Rows.Add(row);
TableCell cell = new TableCell();
row.Cells.Add(cell);
HyperLink hyperLink = new HyperLink();
hyperLink.NavigateUrl = link;
hyperLink.Text = title;
hyperLink.Font.Bold = true;
cell.Controls.Add(hyperLink);

Label label = new Label();
label.Text = description;
cell.Controls.Add(label);
}
protected override void CreateChildControls()
{
Controls.Clear();

if (string.IsNullOrEmpty(rssUrl))
{
ChildControlsCreated = true;
return;
}
using (XmlReader reader = XmlReader.Create(rssUrl))
{
AddContainer();
reader.MoveToContent();
reader.ReadToDescendant("channel");
reader.ReadToDescendant("item");
do
{
using (XmlReader itemReader = reader.ReadSubtree())
{
AddItemToContainer(itemReader);
}
} while (reader.ReadToNextSibling("item"));
}
ChildControlsCreated = true;
}
}
}
Future Enhancement:
Accepting multiple RSS feeds ( DataTable.Merge() )

0 comments: