Generate Rss and Atom Feeds using Asp.Net MVC – part 2

In the previous post Generating Rss Feeds using Asp.Net MVC – part 1, we looked into how to generate Rss Feed using an Asp.Net MVC application. In this short article, we will see how can we generate variable types of Feed by just modifying couple of lines of code.

We need to determine what Feed Format request is coming in from the customer. I have modified the route registrar in global.aspx to accept a default and a custom feed request as well.

routes.MapRoute(
                "Feed", // Route name
                "{controller}/{type}", // URL with parameters
                new { controller = "Feed", action = "Index", type = UrlParameter.Optional } // Parameter defaults
            );

We will just need to mention the Feed or a combination of Feed and Type. Similar urls extension will work

// default, which is Rss
http://codingphobia.com/Feed

// for Atom Feed
http://codingphobia.com/Feed/Atom

We will need to shift some of the ExecuteResult logic out into methods and call appropriate one depending upon request.


        //For Atom Feed request
        private static void WriteToAtomFormatter(ControllerContext context, SyndicationFeed Feed)
        {
            Atom10FeedFormatter atomFormatter = new Atom10FeedFormatter(Feed);
            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))
            {
                atomFormatter.WriteTo(writer);
            }
        }

        //For Default Rss Feed request
        private static void WriteToRssFormatter(ControllerContext context, SyndicationFeed Feed)
        {
            Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(Feed);
            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))
            {
                rssFormatter.WriteTo(writer);
            }
        }

We need to modify our ExecuteResult Method like as follows

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = "application/rss+xml";

            // check if the request is for Atom Feed
            if (context.HttpContext.Request.Url.OriginalString.Contains("Atom"))
                WriteToAtomFormatter(context, Feed);
            else
                WriteToRssFormatter(context, Feed);
        }

And this is all the work. Just with 7 lines of code and bit of modification, we may now generate Atom or Rss feed as per client request. We can also add logic for any Feed Format. Only important thing to work over is the returning ActionResult.

Advertisements

Generating Rss Feeds using Asp.Net MVC – part 1

This is a two part series in which I would explain a bit how can we generate Syndication feed using Asp.Net MVC and Syndication framework. first part will look into how to implement basic structure and second part will explain about how can we use a single line check and generate any type of feed, like Atom, Rss or another as per requirement.

I will start with a custom ActionResult named as FeedActionResult

public class FeedActionResult : ActionResult
{
  public SyndicationFeed Feed { get; set; }
}

We need our FeedActionResult to return our feed as an Object of Type ActionResult. Here is how we do this.

        public ActionResult GetFeed()
        {
            SyndicationFeed feed =
                   new SyndicationFeed("codingphobia.com Feed",
                                       "This is a feed from codingphobia.com",
                                       new Uri("http://codingphobia.com/feed/"),
                                       "somefeedID",
                                       DateTime.Now);
            SyndicationItem item1 =
                new SyndicationItem("Linq To XML: Generate Types with Nested Types using C#",
                                   "This is the content for Test item2",
                                    new Uri("http://codingphobia.com/2010/03/12/linq-to-xml-generate-types-with-nested-types-using-c/"),
                                   "TestItemID",
                                   DateTime.Now);

            List<SyndicationItem> items = new List<SyndicationItem>();

            items.Add(item1);
            feed.Items = items;

            return new FeedActionResult() { Feed = feed };
        }

As ActionResult is an abstract class, we need to provide implementation for the ExecuteResult method which is as follows

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = "application/rss+xml";

            Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(Feed);
            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))
            {
                 rssFormatter.WriteTo(writer);
            }
        }

Now we can call FeedActionResult.GetFeed() from our Controller, dedicated for processing requests for Feeds. Here is how we do this

    public class FeedController : Controller
    {      
        // GET: /Feed/
        public ActionResult Index(string format)
        {
            return new FeedActionResult().GetFeed();
        }
    }

I have used action method Index(string format) with as string parameter here. This will help us to receive requests, for both Atom and Rss based Formats. We will look into this in later Post.

Following is the route settings in the global.asx file

routes.MapRoute(
                "Feed", // Route name
                "{controller}/{action}/{type}", // URL with parameters
                new { controller = "Feed", action = "Index", type = UrlParameter.Optional } 
            );

How to Generate an Rss Feed using System.ServiceModel.Syndication Framework. Part 3

Syndication-Feed provides all the properties we will need to generate a feed for our web site. This article assumes that you have a Data Access layer, which could provide the objects / content and other information needed to publish a feed. I will be using sample variables and objects, which you can replace with originals content / objects

           // Create a raw SyndicationFeed object
            SyndicationFeed feed = new SyndicationFeed();

            // Set the title for the Feed
            feed.Title = new TextSyndicationContent("codingphobia.com articles");

            // set the language you Feed is published in
            feed.Language = "en-gb";

            // set the description for the Feed / Feed resource
            feed.Description = new TextSyndicationContent("Latest Content from codingphobia.com");

            // set the rights information that apply over 
            // the consumption / distribution of the  
            // Feed / content
            feed.Copyright = new TextSyndicationContent("CC");

            // Set the categories under the Feed / content is published
            feed.Categories.Add(new SyndicationCategory("RssFeed"));
            feed.Categories.Add(new SyndicationCategory("cSharp"));
            feed.Categories.Add(new SyndicationCategory("SyndicationFeed"));

            // Set the information about the feed Generator Engine
            feed.Generator = "WordPress3.0";

            // Add the List of Post / Articles / content links 
            // and information to the Feed Object
            List<SyndicationItem> feedItems = new List<SyndicationItem>();

           
            SyndicationItem feedItem1 =
                new SyndicationItem(
                    "Really simple syndication -RSS with .Net. (Intro)",
                    "Rss Feed Fameworks",
                    new Uri("http://codingphobia.com/category/c/page/2/"));
            feedItems.Add(feedItem1);

            SyndicationItem feedItem2 =
                new SyndicationItem(
                    "How to consume an Rss feed using System."+
                    "ServiceModel.Syndication Framework. (Part 1)",
                    "Consume Rss Feed",
                    new Uri("http://codingphobia.com/2009/07/06/how-to-consume-an"+
                    "-rss-feed-using-system-servicemodel-syndication-framework-part-2/"));
            feedItems.Add(feedItem2);

            SyndicationItem feedItem3 =
                new SyndicationItem(
                    "How to consume an Atom feed using Argotic Framework. (Part 2)",
                    "Consume Atom Feed",
                    new Uri("http://codingphobia.com/2009/07/09/how-to-consume-an-atom"+
                    "-feed-using-argotic-framework-part-2/"));
            feedItems.Add(feedItem3);

            // Set the url forthe image / logo for your Feed
            // Displayed on the side of the feed page
            feed.ImageUrl = new Uri("http://codingphobia.com/imageUrl");

How to consume an Rss feed using System.ServiceModel.Syndication Framework. (Part 1)

System.ServiceModel.Syndication provides several classes which are great for the manipulation of a feed resource. Using SyndicationFeed class

could helps us retrive all the required bits about particular feed resource and latest content, once the feed is loaded.

Below is sample program which demonstrates a syndicationFeed Object in action.

using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Xml;

namespace SyndicationFeedManager
{
    public class RssFeedManager
    {
        public void ParseRssFeed()
        {
            // Url To load Feed From
            string urlToLoadFeed = "";

            // Load Feed, Load Method requires and object of Xmlreader object
            SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(urlToLoadFeed));           

            // get Title of Feed
            string feedTitle;
            if (feed.Title != null)
            {
                feedTitle = feed.Title.Text;
            }

            // get Short description of the feed
            string feedDescription;
            if (feed.Description != null)
            {
                feedDescription = feed.Description.Text;
            }

            // get the Icon url of the feed
            string feedIconUrl;
            if (feed.ImageUrl != null)
            {
                feedIconUrl = feed.ImageUrl.AbsoluteUri;
            }

            // get Image Url of the feed,  A snapshot
            string feedImageUrl;
            if (feed.ImageUrl != null)
            {
                feedImageUrl = feed.ImageUrl.AbsoluteUri;
            }

            // get copy right info of feed
            string feedCopyRights;
            if (feed.Copyright != null &amp; !feed.Copyright.Text.Equals(""))
            {
                feedCopyRights = feed.Copyright.Text;
            }

            // get the categoried under whic feed is filed
            List feedCategories = new List();
            if (feed.Categories != null)
            {
                foreach (SyndicationCategory category in feed.Categories.ToList())
                {
                    if (category.Name != null)
                    {
                        feedCategories.Add(category.Name);
                    }
                }
            }

            // get the language feed has been published in
            string feedLanguage;
            if (feed.Language != null &amp;&amp; feed.Language.Length &gt; 1)
            {
                feedLanguage = feed.Language;
            }
        }
    }
}

Really simple syndication -RSS with .Net. (Intro)

In this series of articles we will go through the process of creating and consuming an RSS Feed using the API built into Microsoft .Net Faramework and another papular framework available in the market known as Argotic.

In the preceeding articles after intro, we will go through in detail about:

We will be using Visual C#.Net as our programming language and the available API’s accordingly

First things first:

what is Rss and what does it stand for  ??  Really simple syndication. a more better way to explain is:

It the list of hyper-links of  an on-line resource, ordered in particular manner with the minimum bits of information required to get to that resource.

Most of the modern browser fully suport this feature and come with pre installed Rss parsers.(Chrome being more focused on its performance is currently not supporting this feature but there are some third party option available like Feed Viwer . Another easy is to use Google Reader )

What exactly is Rss ?

Rss is an xml file, generated in one of the standard formats, designed for the purpose. These formats differ slightly and and can hold information depending upn the content they represent. Following are the Rss Format with most commonly in use.

RSS

  • RSS 0.90 (the original Netscape RSS version)
  • RSS 1.0
  • RSS 1.1
  • RSS 2.0

Atom

OPML

BlogML

Rss and Atom being mostly used, we will be working on how to generate and consume feed in these formats.

Frameworks

Microsoft .Net framework has a built in rich library to work with most of the formats named as  System.ServiceModel.Syndication with its most useful class SyndicationFeed.

There is another third party framework known as Argotic , which also provides several classes shich make it very helpful to work woth RSS content

Another third Party framework known as Rss.Net is also papular and is used in the development of  a lot  of Feed related Web Applications.

No particular framework is more papular than other. The difference noticeable is, System.ServiceModel.Syndication has been tested and proved to be 9 times faster than Argotic Framework and is recommended by many developers for that reason. On the other hand Argotic comes with wide set of  rich classes, which provide not only handling implementation of a feed service in commonly used formats very easy but also for less common but important formats, like BlogML.

So it is the choice between the efficiency of your application vs efficiency in development. In the end choice is always yours.