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.
Posts