WCF Web Programming or: How I Learned to Stop Worrying and Love Uri Templates

Using WCF in web programming scenarios is much simplified in Orcas beta 2 (see http://hyperthink.net/blog/CategoryView,category,indigo.aspx and scroll down for more discussions).  Maybe you want to write an app that searches Flickr, how can you use WCF?  Well, define an interface that exposes the functionality you need:


interface IFlickrSearch






rsp Search(string appId, string searchTerms, string extras, int perPage);


The Flickr API is very rich, so this is just the tip of the iceberg, but just this little bit of code accomplishes a lot. We have all the WCF v1 attributes (ServiceContract, OperationContract) and some new stuff. WebGet says the request will be a GET and UriTemplate describes how the parameters will be turned into the uri for the request. This provides a great deal of flexibility in defining your interface to the service you're programming against. The Bare BodyStyle specifies to the serializer there won't be wrapper element named SearchResponse on the response. XmlSerializerFormat is another holdover specifying the XmlSerializer, and rsp is a type generated with xsd.exe to deserialize the response.

Now we're ready to call Flickr:

WebChannelFactory<IFlickrSearch> factory =

new WebChannelFactory<IFlickrSearch>(new Uri("http://api.flickr.com"));

IFlickrSearch channel = factory.CreateChannel();

rsp flickrRsp = channel.Search(AppId, searchTerms, Extras, perPage);

And that's it.

Maybe you're saying XmlSerializer is way too 20th century and you'd like use something more 21st, like XLinq.


interface IFlickrSearch


[WebGet(UriTemplate = "services/rest/?method=flickr.photos.search&api_key={appId}&tags={searchTerms}&extras={extras}&per_page={perPage}",

BodyStyle = WebMessageBodyStyle.Bare)]


XElement Search(string appId, string searchTerms, string extras, int perPage);


We've just taken out the XmlSerializerFormat attribute and replaced the rsp type with XElement. Now we can use Linq and turn the Flickr search into a SyndicationFeed (another new WCF Orcas feature):

SyndicationFeed feed = new SyndicationFeed();

feed.Title = new TextSyndicationContent("Flickr search");

feed.Items =

from photos in flickrXml.Elements("photos").Elements("photo")

select SyndicationItemFromXElement(photos);

Just add this to a service and now you have a Flickr search you can subscribe to in the feed aggregator of your choice.