Creating an OData Server Quickly

Windows Phone Tutorial

There are numerous ways to access data from Web Services.  To explore these we need a simple server that exposes data we can interact with from a Windows Phone Application.

To facilitate this, we’ll build an ASP.NET/MVC 3 application that uses  Entity-Framework Code-First (Magic Unicorn Edition)  on top of SQLCE4, and we’ll expose the data in a WCF Data Service using the Open Data (OData) Protocol   This can be done surprisingly quickly and is highly reusable.

We’ll start with a dead-simple model (and build from there in later postings).

Instant Server – just add code

Create a new ASP.NET / MVC 3 application and name it SimpleServer.  At the Project Template dialog, choose Internet Application.

The first task is to add the Entity Framework Code-First library with SQL  Server NuGet Compact 4.0.  This is easily accomplished with NuGet.  Open the Add Library Package dialog, click on Online/All and in the search window type EFCodeFirst.SQL – the package you need will come up as shown in the figure.

Click to install and that package and all its dependencies will be loaded into your project.  You will need to accept the licenses in the “click to accept” dialog.

Adding the Model

Right click the Models folder and add a new class named Book.  Here’s the complete source code for the Book class:

namespace SimpleServer.Models
{
    public class Book
    {
        public int ID { get; set; }
        public string ISBN { get; set; }
        public string Title { get; set; }

        public class BookContext : DbContext
        {
            public DbSet<Book> Books { get; set; }
        }
    }
}

Notice that the Book class has no attributes or special interfaces, nor any specific base class. It is a POCO and all that is needed is the Context (BookContext), which we’ll use to access the entities in the application.  The only requirement for the context is that it inherit from DbContext and hold one or more DbSet.

We need some testing data to expose from our service. The simplest way to get that into our database is to modify the CreateCeDatabaseIfNotExists class in AppStart_SQLCEEntityFramework.cs by adding some seed data to the Seed method

 protected virtual void Seed(TContext context)
 {
     var bookContext =
           context as SimpleServer.Models.Book.BookContext;
     bookContext.Books.Add( new Models.Book
     {
         ID = 1,
         ISBN = "143023816X",
         Title = "Migrating to Windows Phone"
     } );

     bookContext.Books.Add( new Models.Book
     {
         ID = 2,
         ISBN = "1430237473",
         Title = "Programming Reactive Extensions"
     } );

     bookContext.Books.Add( new Models.Book
     {
         ID = 3,
         ISBN = "0672333317",
         Title = "Teach Yourself C++ In 24 Hours"
     } );
 }

Also in SQLCEEntityFramework.cs, at the top of the file, be sure to uncomment the setInitializer and to replace the context name,

public static void Start() {
    DbDatabase.DefaultConnectionFactory =
     new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

    DbDatabase.SetInitializer(
       new CreateCeDatabaseIfNotExists<
          SimpleServer.Models.Book.BookContext>());
}

Add a new WCF Data Service to the project (right-click the project / Add New Item / Web / WCF Data Service).  Name it BookDataService.

Open the codebehind for the service and replace the code for the class with this code that makes debugging easier by including exception details in faults and using verbose errors (remove all of this when the service is working).

[ServiceBehavior( IncludeExceptionDetailInFaults = true )]
public class BookDataService :
    DataService< SimpleServer.Models.Book.BookContext >
{
    public static void InitializeService(
        DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule(
            "*", EntitySetRights.All );
        config.DataServiceBehavior.MaxProtocolVersion =
            DataServiceProtocolVersion.V2;
        config.UseVerboseErrors = true;
    }
}

You can see the output of the service’s collection by browsing to http://localhost:[port number]/BookDataService.svc/Books

Hey! Presto! Instant OData Server.

Share

About Jesse Liberty

Jesse Liberty is an independent consultant and programmer with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP, Microsoft MVP and Telerik MVP.
This entry was posted in Data, Essentials, Mango, Mini-Tutorial and tagged . Bookmark the permalink.

4 Responses to Creating an OData Server Quickly

  1. Wilhelmina says:

    A short discussion on Myfreecam Token Hack

    There are many online performances available that
    provide performances like, ranging from pole dance to
    strip tease by female models. Myfreecam token hack is such a token by which you are able to
    get some discount on seeing such performances. Let us describe about these tokens and other products
    below.
    About the website:
    The customers are allowed to enjoy private shows and tip performers by using virtual Myfreecam tokens.

    The customers are also supposed to chat with the performers through the performer’s channel.
    A webcam and a microphone are used by the performers in order to
    broadcast their performances. Both customer and performer are supposed to send messages
    and mail to each other. A customer automatically becomes a lifetime member after purchasing his/her first token. The customer
    remains member even if he/she runs out of the tokens.
    The customers are allowed to get an exciting discount on the prices of
    many tokens. A customer can pay the bill through discreet billing by credit card.
    The monthly token buyers are supposed to avail the reward
    tokens. You can get the tokens in the form of token packages that are available to you after becoming
    a premium member for few months. A distinct kind of software is used by myfreecam token hack (Wilhelmina).

    You can experience spy shows, group shows, and personal shows buying these kinds of tokens.
    Though these tokens are so costly but Myfreecam token hack helps you to get
    shows for free. It basically provides you a free access to the shows.
    This token is too useful to a customer to view the website for a short span of time.
    After purchasing the tokens for the time the membership
    of a customer is made for a lifetime. Normally
    the website provides many bugs in the code that allows Myfreecam token hack
    users to fiddle the security of access and get tokens
    for free to buy using this token.
    It is all about Myfreecam token generator:
    Myfreecam token generator is a kind of free software which
    helps to generate free tokens for this token. A NET framework is the basement
    of it. The customer is supposed to create an account first in order to run the generator application for getting the choices of the numbers of
    the Myfreecam token hack. Some features of this are described below: (1)
    It is so easy to use and being undetectable provides an auto update regarding
    the version. (2) It basically works on all internet browsers (internet explorer,
    chrome and Firefox). (3) In any case the hack is patched
    the update will be provided to ensure 100% satisfaction within 24 hours.
    (4) It works smoothly in all countries of all continents.
    (5) In order to find the faults it is tested on a daily basis as the company gives priority to the functionality.
    (6) The customer can use Myfreecam token hack as many times as he/she
    wants without any error.
    Conclusion
    The customers are allowed to purchase 5000 tokens
    maximum in a day. After becoming the permanent member one is allowed to get these tokens from the
    website Myfreecam token hack. At least it can be said that these tokens can be used in many ways for
    the customers.

  2. Johnesh says:

    Great article. oData version 3 is now available and allows use of dbContext directly.Initially one had to override the CreateDataSource method to manually get the ObjectContextto provide to the data services. http://www.microsoft.com/en-us/download/details.aspx?id=29306

  3. Vagif Abilov says:

    Are you sure WCF Data Services will be able to use DbContext-derived class directly? AFAIK, since DataService was designed prior to EF 4.1, it needs and adaptor from DbContext to ObjectContext. Luckily it’s easy to add. Here are some info on this:

    http://blogs.msdn.com/b/writingdata_services/archive/2011/06/15/entity-framework-4-1-code-first-and-wcf-data-services.aspx

    http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/0c1f8425-55f4-4600-9605-a925220d5a25

  4. Pingback: Windows Azure and Cloud Computing Posts for 9/20/2011+ - Windows Azure Blog

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>