Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

Custom RssFeed WebPart in SharePoint 2010

Custom RssFeed WebPart in SharePoint 2010

Here are the steps and the code snippet for creating a custom webpart to display items or news via rss feed.

1. Open the VS and add a new blank solution.
2. Now in your Solution say “RssFeedPackage” add a new item then choose add a webpart. Lets name it as RSSFeedWebPart.
Please note : You can directly create a webpart solution and do not necessarily have to add it as an item. I did this because I wanted to add some more features in the same solution.
3. Next, you need to add some logic to the RSSWebPart WebPart. Edit the RSSWebPart.cs class to include the code below. I have added a custom property to receive the Rss feed url for the webpart.

Code goes like this :

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace RssFeedPackage
{

[ToolboxItemAttribute(false)]
public class RSSFeedWebPart: WebPart
{

[WebBrowsable(true)] [Personalizable(PersonalizationScope.Shared)]
public string RSSUrl
{
get; set;
}

protected override void RenderContents(HtmlTextWriter writer)
{

RSSFeed feed = new RSSFeed(RSSUrl);
HyperLink newLink = new HyperLink();

foreach (RSSItem singleRssItem in feed)
{
newLink.Text = singleRssItem.Title;
newLink.NavigateUrl = singleRssItem.Href;
newLink.Target = “rssSite”;
newLink.RenderControl(writer);
writer.WriteBreak();
}
base.RenderContents(writer);
}
}
}

//Code for RSSFeed class

internal class RSSFeed : List
{
internal RSSFeed(string RssURL)
{
try
{
XmlDocument rssDoc = new XmlDocument();
XmlTextReader xRead = new XmlTextReader(RssURL);
rssDoc.Load(xRead);
XmlNodeList xNodes = rssDoc.SelectNodes(“./rss/channel/item”);
foreach (XmlNode xNode in xNodes)
{
this.Add(new RSSItem(xNode)) ;
}
}
catch (Exception)
{
this.Add(new RSSItem());
}
}
}

//Code for RSSItem

internal class RSSItem
{
public string Title { get; internal set; }
public string Href { get; internal set; }
internal RSSItem()
{
Title = “Feed not available at this time” ;
Href = “~” ;
}
internal RSSItem(XmlNode xNode)
{
Title = xNode.SelectSingleNode(“./title”).InnerText;
Href = xNode.SelectSingleNode(“./link”).InnerText;
}
}

4. Now build and deploy the webpart.

5. Finally, Insert the webpart in your webpart page and specify the Rssurl in Edit this WebPart -> RssUrl box.

No comments:

Post a Comment