OdeToCode IC Logo

Mashups with SyndicationFeed and LINQ

Monday, March 17, 2008

I was experimenting with the new SyndicationFeed class in 3.5 earlier this year and devised a mashup LINQ query:

string[] feedUrls = { "https://odetocode.com/blogs/scott/rss.aspx",

var items =
from url in feedUrls
let feed = SyndicationFeed.Load(XmlReader.Create(url))
from item in feed.Items
where item.PublishDate > DateTime.Now.AddDays(-30)
orderby item.PublishDate descending
    select item;

// display the most recent 15 items
foreach (SyndicationItem item in items.Take(15))
Console.WriteLine("{0} : {1}",

The code is able to filter and sort RSS items from an arbitrary number of blogs with a 6 line query expression. I was thinking of this code when I ran across Scott Hanselman's Weekly Source Code 19 – LINQ and more What, Less How. Scott's reader David Nelson had the following observation:

I disagree with Siderite, in that I think the LINQ example is more readable than the iterative example; however, as has been pointed out, it leaves no room for error handling or AppDomain transitions. This is a problem with LINQ in general; in trying to make everything very compact, it leaves too little room to maneuver.

The LINQ query I'm using isn't production code. If just one blog is down and the XmlReader throws an exception, the entire operation is borked. One solution is to wrap the feed reading into a method that uses exception handling and returns an empty SyndicationFeed in case of an exception - then invoke the method from inside the query. Could anything else go wrong? Sure - one null PublishDate on an item and again we'd be borked. Bullet-proofing a LINQ query might take some work, especially when dealing with third party types.  

As LINQ moves us into the "What" instead of the "How", it might be harder to see these types of error scenarios. LINQ is a fantastic technology, but like everything in software, it is a good idea to look the gift horse in the mouth.