World’s simplest OData service

I get frustrated sometime trying to play around with new Microsoft technologies.  The process usually involves;  install this CTP, apply this hotfix, create a project using this template, and this item using another template.  By then end I may have something working but I don’t know what magic happened behind the scenes.

Here is a bare bones implementation of an OData service, no magic allowed (Ok, without actually going to the command line compiler). 

What you will need for this experiment is:

1) .Net Framework 3.5 sp1

2) A new Visual Studio 2008 console application

3) These references

    • System
    • System.Core
    • System.ServiceModel          <—This brings in the WCF stack
    • System.ServiceModel.Web <—This brings in the Web friendly WCF service host
    • System.Data.Services         <—This brings in the OData service host

 

4) and this code

using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Linq;


namespace ODataConsoleService {
    class Program {
        static void Main(string[] args) {

            string serviceAddress = "http://localhost:998";
            Uri[] uriArray = { new Uri(serviceAddress) };
            Type serviceType = typeof(CustomerDataService);

            using (var host = new DataServiceHost(serviceType, uriArray)) {
                host.Open(); 
                Console.WriteLine("Press any key to stop service");
                Console.ReadKey();
            }

        }

    }

    // Expose IQueryable properties as read-only Atom collections
    public class CustomerDataService : DataService<CustomerService> {
        public static void InitializeService(IDataServiceConfiguration config) {
            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
        }
    }


    // Expose list of customers Customer as IQueryable
    public class CustomerService {
        private List<Customer> _List = new List<Customer>();

        public CustomerService() {

            _List.Add(new Customer() { ID = 1, Code = "BLAH", Name = "Blah" });
            _List.Add(new Customer() { ID = 2, Code = "Bob", Name = "Bob's Hardware" });
            _List.Add(new Customer() { ID = 3, Code = "Bill", Name = "Bills Fishmongers" });
        }

        public IQueryable<Customer> Customers {
            get {
                return _List.AsQueryable<Customer>();
            }
        }

    }

    // Entity to expose in atom:Entry
    public class Customer {
        public int ID { get; set; }  // ID is required to be a viable OData entity
        public string Code { get; set; }
        public string Name { get; set; }
    }

}

 

That’s it.  That’s all you need to expose a complete Atom Pub compliant service exposing your objects.

Once you have that, you can Run the program and use a web browser to browse to http://localhost:998 to see the collections.   Don’t forget to look in the magic url http://localhost:998/$metadata  Sorry, some magic I am still trying to figure out how to remove!

Credit goes to Alex James and Phani for getting me most of the way there.

15 thoughts on “World’s simplest OData service

  1. Good sample – should be one as simple for every new technology! Seems that quite often the technology samples try to say: “Se all that I can do!” :)

    However, I had this problem: “HTTP could not register URL http://+:998/. Your process does not have access rights to this namespace”.

    Solved with this advice, though: “netsh http add urlacl url=http://+:8000/ user=DOMAINUserName” (http://blogs.msdn.com/amitlale/archive/2007/01/29/addressaccessdeniedexception-cause-and-solution.aspx)

  2. Darrel,

    Actually ID is not required for an valid OData feed.
    You can use {ClassName}ID too.

    Or if you want full control use the [DataServiceKey("keyproperty")] attribute on your class.

    Alex

  3. This is great! Thank you, I agree there are not enough simple implementations of OData with WCF Data Services out there. This really helped me out and gave me a good starting place to play around with WCF Data Services without EDM.

    • Try using Fiddler to view the response. Web browser try to do all sorts of magic based on what they think you want them to do. Fiddler will show you really what is happening.

  4. Thanks for this post – exactly what I was looking for.

    Just wondering if you can shed some light on OData updates/inserts (PUT/POST)?
    The only way I’ve found that works is to use Entity Framework.

    Thanks,
    Chris

    • You should be able to treat the service like a regular Atom Pub service, however the atom content will need to formatted with the EDMX instance schema format.

  5. Thank you! This post helped a lot. Wanted to tinker with OData without an actual database running, and every tutorial starts with creating a database/EF.

  6. Really the simplest o data service I have ever come across
    please give examples for CRUD operations .
    Thanks in advance
    Regards,
    sateesh munagala

  7. Thanks and it is a nice Article.
    One minor detail is missing. On the custom class, we need to add the following attribute:
    [DataServiceKey("ID")]
    public class Customer
    {
    …..
    }

  8. Alex, thanks for your code. I’m trying to consume the data from the web service (it works since I can see it in a browser), but with no luck. Could you add a super-simple VB or C# example to accomplish it?

Leave a Reply

Your email address will not be published. Required fields are marked *

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=""> <strike> <strong>