Wednesday, December 12, 2007

Consuming My Simple REST Service with ADO.NET Data Services ("Project Astoria")

In my previous post, I showed a simpler way of creating a RESTful web service using ADO.NET Data Services.  In this post, I wanted to explore how difficult it is to consume those services.

I'm going to create a console application that will be the client using the service that returns customers from the Northwind database.  After I create the console application, I'm going to need to add a reference to the Microsoft.Data.WebClient assembly which can be found in your Program Files\Reference Assemblies\Microsoft\Framework\ASP.NET 3.5 Extensions directory.

After making that reference, I need to create a class that is identical in form to the object that is being serialized by the service.  So, in my case, the Customer class that I am using for my service needs to look like this:

public class Customer
{
    public string CustomerID { get; set; }
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
    public string ContactTitle { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Region { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
    public string Phone { get; set; }
    public string Fax { get; set; }
}

From there, in my entry method, I can create a "WebDataContext" object that points to the service:

WebDataContext context = new WebDataContext(http://localhost:50508/Astoria/MySimpleService.svc);

After I have this context, I can do all sorts of interesting things.  One thing I can do is query the data by creating a WebDataQuery object like this:

WebDataQuery<Customer> customers =
    context.CreateQuery<Customer>("/Customers?$orderby=CustomerID");
 
foreach (Customer customer in customers)
{
    Console.WriteLine(customer.ContactName);
}

Even better, I can throw in some Lambda Expressions with LINQ, and use LINQ to create the queries for me.

var customers = from p in context.CreateQuery<Customer>("Customers")
                where p.CompanyName == "Alfreds Futterkiste"
                select p;

This way is a great way to learn more about the URI format of the queries of the service, because you can set a break point after you've created the query and get the actual URL that is sent when the query is executed.

shows mouseover of query

Again, really awesome stuff.  Although, I still need to do some due diligence on PUT, POST and DELETE activities of the REST service.

References

Man vs. Code - Linq to REST - Andy Conrad
Consuming ADO.NET Data Services - .NET Client Library