Thursday, July 15, 2010

How to Serialize a SyndicationFeed Object To Be Returned From WCF

Recently I have been working with the SyndicationFeed class in the System.ServiceModel.Syndication namespace. It allows us as developers to work nicely with Atom 1.0 and RSS 2.0 content. A problem arose when I needed to return this object from RSS to a consuming Silverlight client. The problem was that the raw SyndicationFeed class is not serializable, so I needed a solution to serialize the Feed and return it.

This was one time I was happy to find that no custom serialization methods, or mimicking all property values in my own DataContract to return was going to have to be the solution. Instead there are 2 nice classes in the same namespace that do exactly this for us: the Atom10FeedFormatter & Rss20FeedFormatter classes.

In my case I was working with Atom 1.0 content so I was able to use that Serialization class. The solution was simple. Alter my WCF service to return a type of 'Atom10FeedFormatter' defined both on the OperationContract and implementing service method. Then the client can define the return type to receive, and place it right back into a SyndicationFeed object if desired. There are also Atom10FeedFormatter(Of TSyndicationFeed) & Rss20FeedFormatter(Of TSyndicationFeed) classes to serialize classes that derive from those types, and there are all the same classes for the 'SyndicationItem' object as well. Needless to say there is some flexibility in serializing this data to be returned.

So let’s take a look at the code; 1st the code to extract a SyndicationFeed (i.e. from an RSS link off the web).

'Make a call to extract RSS information from the web
Dim proxy As New WebClient()
'Load stream into a reader
xmlRdr = XmlReader.Create(proxy.OpenRead(New Uri("http://rss.cnn.com/rss/cnn_topstories.rss")))

'Load syndicated feed (Atom)
Dim feed As SyndicationFeed = SyndicationFeed.Load(xmlRdr)
Next the code to Return from the method the Atom10FeedFormatter. I do this inline in the Return statement as it is easiest:

Return New Atom10FeedFormatter(feed)
Lastly, the client code to receive the Atom10FeedFormatter and place it back into a SyndicationFeed object. You may wish to do this before binding to controls.

Dim wcfSrv As New MyWCFService.MyWCFServiceClient
'Create the Formatter which will be returned from the RSS call below
Dim MyRssSyndicationData As Atom10FeedFormatter
MyRssSyndicationData = wcfSrv.RssFeedData()

'Load the returned formatter back into a SyndicationFeed object if desired
Dim RssDataFeed As SyndicationFeed = MyRssSyndicationData.Feed
So that's it! If you want to learn more about these classes that make serializing SyndicationItem or SyndicationFeed classes so easy, take a look to the following link:

System.ServiceModel.Syndication Namespace

No comments:

Post a Comment