TopMenu

Creating OData service using WCF DataService

What is OData? This should be first question if you're new to this term. Here is the little brief about it -

“The Open Data Protocol (OData) is a Web protocol for querying and updating data that provides a way to unlock your data and free it from silos that exist in applications today. OData does this by applying and building upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSONto provide access to information from a variety of applications, services, and stores. The protocol emerged from experiences implementing AtomPub clients and servers in a variety of products over the past several years.  OData is being used to expose and access information from a variety of sources including, but not limited to, relational databases, file systems, content management systems and traditional Web sites.”

Reference – http://www.odata.org

Want to know more like What, Why and How? visit here http://www.odata.org/introduction
Now once you go through the specification of OData you’ll get to know where it can fit into your requirement when designing service architecture.

Let’s not deep digging these decision making arguments and get back to the business i.e. How can we create an OData service using WCF DataService?

So go ahead and Launch your VisualStudio 2010 (or 2012 if you have that one installed. its available as RC version for free when I’m writing this article.)
Now create a web project or rather add a class library project (Lets keep little layering and separation of business)

below are simple and step by step walkthrough, keeping in mind someday some beginner(new to VS) might be having trouble with written instructions.

image
image
Name it as Demo.Model as we’re creating a sample service and this will work as Model (Data) for our service.

Now go ahead and add a new item –> ADO.Net Entity
image
Name it as DemoModel.edmx. when you click Add, a popup will be waiting for your input. So either you can generate your entities from database or you can just create an empty model which further can be used to generate your database. Make your choice.

But we’re simply going to use the existing database as I already have nice to have test database from Stackoverflow dumps.

SNAGHTMLcff6358
Click Next> and get your connection string from NewConnection and you’re ready to click Next> again ..
SNAGHTMLcfff0e7
select your Database object that you want to include into your Entities. SNAGHTMLd03a70c
For creating the OData service we only need the Tables. So after clicking the finish your Entities diagram should look like this. Here’s the important note; “The relationship between the entities should be well defined because the OData will be searching/locating your related entities based on your Query(Know about URI Queries)
image
We’re close enough to finish the job more than 50% work is done to create the service. Forget about the time when we used to define/create/use the client proxy and other configuration settings including creating the Methods for eveytype of data required.
(Note:- This post will only show you how to get the data from OData service. I can write some other time about Create, Delete, Edit using PUT, DELTE, POST http requests.)
Now Go ahead and add new Web project (Should choose Asp.net Empty website) from the templates
image
Add the project reference Demo.Model to the newly added website.
image
Now add a new item in the web project i.e. WCF Data service.
SNAGHTMLd348f77
Now open the code behind file of your service file and write this much of code.
  1.      [JSONPSupportBehavior]     
  2.     //[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]   //- for debugging
  3.     public class Service : DataService<StackOverflow_DumpEntities>
  4.     {         
  5.         // This method is called only once to initialize service-wide policies.
  6.         public static void InitializeService(DataServiceConfiguration config)
  7.         {
  8.             config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);             
  9.             //Set a reasonable paging site
  10.             config.SetEntitySetPageSize("*", 25);            
  11.             //config.UseVerboseErrors = true;  //- for debugging
  12.             config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
  13.         }
  14.  
  15.         /// <summary>
  16.         /// Called when [start processing request]. Just to add some caching
  17.         /// </summary>
  18.         /// <param name="args">The args.</param>
  19.         protected override void OnStartProcessingRequest(ProcessRequestArgs args)
  20.         {
  21.             base.OnStartProcessingRequest(args);            
  22.             //Cache for a minute based on querystring
  23.             HttpContext context = HttpContext.Current;
  24.             HttpCachePolicy c = HttpContext.Current.Response.Cache;
  25.             c.SetCacheability(HttpCacheability.ServerAndPrivate);
  26.             c.SetExpires(HttpContext.Current.Timestamp.AddSeconds(60));
  27.             c.VaryByHeaders["Accept"] = true;
  28.             c.VaryByHeaders["Accept-Charset"] = true;
  29.             c.VaryByHeaders["Accept-Encoding"] = true;
  30.             c.VaryByParams["*"] = true;
  31.         }
  32.  
  33.         /// <summary>
  34.         /// Sample custom method that you OData also supports
  35.         /// </summary>
  36.         /// <returns></returns>
  37.         [WebGet]
  38.         public IQueryable<Post> GetPopularPosts()
  39.         {
  40.             var popularPosts =
  41.                 (from p in this.CurrentDataSource.Posts orderby p.ViewCount select p).Take(20);
  42.             
  43.             return popularPosts;
  44.         }
  45.     }

Here we added some default configuration settings in InitializeService() method. Take a note that I’m using DataServiceProtocolVersion.V3 version. This is latest version for OData protocol in .Net, you can get it by installing the SP for WCF 5.0 (WCF Data Services 5.0 for OData V3) and replacing the references of System.Data.Services, System.Data.Services.Client to Microsoft.Data.Services, Microsoft.Data.Services.Client.

Otherwise not a big deal you can still have your DataServiceProtocolVersion.V2 version and It works just fine.

Next in the above snippet I’ve added some cache support by overriding the method OnStartProcessingRequest().

And also I’m not forgetting about the JSONPSupportBehavior attribute on the class. This is open source library that enables your data service to have JSONP support.

First of all you should know why and what JSONP do over JSON. keeping it simple and brief:

i) Cross domain support

ii) Embedding the JSON inside the callback function call.

Hence.. We’re done creating the service. Wondered!! don't be. Now let’s run this project and see what we’ve got. If everything goes fine then you’ll get it running like this.

image

Now here’s the interesting part.

Play with this service and see the OData power. Now you’ve seen that we didn’t have any custom method implementation here and we’ll be directly working with our entities using the URL and getting the returned format as Atom/JSON. :) .. Sounds cool?

If you have LINQPAD installed then launch it otherwise download and install it from here.

Do you know your LINQPAD supports the ODataServices. So we’ll add a new connection and select WCF Data service as our datasource.

image

Now click next and enter your service URL.(Make sure the service that we just created is up and running)

image

The moment you click OK you’ll see your all entities in the Connection panel.

image

Select your service in the Editor and start typing your LINQ queries

image

I need top 20 posts order by View count.. blah blah. So here is my LINQ query.
  1. (from p in Posts
  2. orderby p.ViewCount
  3. select p).Take(20)

Now run this with LINQPAD and see the results.

image

Similary you can write any nested, complex LINQ queries on your ODataService.

Now here is the Key of this, The root of the whole post ..

image

This is OData protocol URI conventions that helped you filtering, ordering your data from entities. You in the end of this article you’ve just created and API like Netflix, Twitter or anyother public API.

Moreover, We used JSONPSupportBehavior so you can just add one more parameter to above url and enter it in browser and go..

image

In the next post we’ll see how to consume this service simple in a plain HTML page using Javascript. Keep an eye on the feeds.. stay in touch.

2 comments:

  1. What is the Scope of its implementation

    ReplyDelete
  2. Thanks for the Creating OData Service using WCF Dataservice. Are you planning on following up on Create, Update and Edit soon?

    ReplyDelete