Tuesday, September 9, 2008

ADO.NET Data Services Part - II

In part – I of this series, we saw how we can perform GET operations over the web with ADO.NET Data Services. But any data model should also allow inserts, updates and deletes. In ADO.NET Data Services, you can do that by using the appropriate HTTP header and passing the corresponding values.


 


Data Manipulation


 


For eg. A simple insert with ADO.NET Data Services will look like below


 


            NorthwindEntities test = new NorthwindEntities(new Uri("http://localhost:6129/NorthwindDataService.svc"));


            Suppliers addSupp = new Suppliers();


            addSupp.CompanyName = "test supplier add from web client";


            test.AddToSuppliers(addSupp);


            test.SaveChanges();


 


This in-turn sends a HTTP POST Request with the Supplier Name enclosed in the given format. In this case, the ATOM XML will look something like


 


 


 


 


 


 



ATOM:


<entry  xmlns:ads="http://schemas.microsoft.com/ado/2007/08/dataweb"   


        xmlns="http://www.w3.org/2005/Atom">


  <content type="application/xml">


    <ads:SupplierName> test supplier add from web client </ads:SupplierName>


  </content>


</entry>


 


You can similarly do Update and Delete Operations. For update, the HTTP header you would use is HTTP PUT and for Delete, it would be HTTP DELETE. You will hardly have to code the HTTP Headers yourself but it is always good to know.


 


Advantages of ADO.NET Data Services


 


There could be a lot of places where you could be thinking about using ADO.NET Data Services. There are a few that come to my mind right away


 


1.       Support for AJAX based frameworks


 


Use of the JSON format makes it much easier for silverlight based applications to get and manipulate records. Before ADO.NET Data Services, SILVERLIGHT applications had to use AJAX to manipulate the records. This way building RIA becomes a lot easier.


 


2.       Enables use of HTTP Caching infrastructure


 


Since ADO.NET uses REST it can use HTTP Caching infrastructure to make sure a lot of data is cached. Compare this with traditional services which are predominantly stateless. This way there is potential to reduce a lot of network traffic.


 


3.       Underlying Data Source is completely encapsulated


 


With ADO.NET Data Services in place, you can build your Data Access Layer which is independent of the underlying data storage technology. Suddenly you are not bothered about pooling connections, using the right providers. All you are worried about is whether you have access to the URI.


 


4.       Separate Control Operations from queries\stored procedures


 


Let me take an example. Suppose you wanted to write a stored procedure that gives you the list of the contacts in your application. Your user interface has a sort feature. To implement sort, you have two options viz. a) Get the data in a dataset and sort the records of the dataset or b) write two stored procedures that do sorting asc or desc. Now imagine this is the ADO.NET Data Services world. To sort or filter your records you don’t need to change your stored procedure all you need to change is the URl. That does make things simple isn’t it?


 


That’s it for now. In Part –III we will actually be creating ADO.NET Data Services and using that from a client that we will build. So back in a week with the next part.

Tuesday, September 2, 2008

Berba Joins Manchester United


Atlast!!! The saga is over. The question has been answered. Though Manchester United might have left it quite late, they eventually sealed the striker’s transfer to Old Trafford with minutes to go for the transfer deadline. The devils gave their fans some anxious moments but people who know Sir Alex will also realize that more often than not, he gets what he wants, be it signings or letting players go.


 


Berba’s 27 goals in 70 games might not match what Klaas Jan Huntelaar, also whom United were having an eye on, has done in Ajax (He has scored 70 goals in his 82 appearances for the club since 2005) but one thing Berba has that Huntelaar doesn’t is his experience in the Premier League. Die hard soccer fans will tell you how different the Premier League is to any other European league and it needs a lot of acclimatization to turn out your star performances. With the injury concern to Ronaldo and Louis Saha’s transfer to Everton Sir Alex needed somebody who he could play in the eleven from Day One.        A lot of articles have claimed that Berba is the missing piece in the Man U jigsaw. I am not so sure. I think Man U are going to have to play their best football in 3 years to match or even top what they did last season. Closer to home, Chelsea are not going to be easy to beat and in the Serie A the Milans are looking quite strong.


 


The next two weeks are going to be interesting. Man U play Liverpool and Chelsea and the outcomes of these matches could give us pointers which way the season is going. I am curious to see who Fergie plays. Both these are tough outings and Fergie will want his best men on the pitch. He will ofcourse have an eye on the Match Day 1 of the Champions League as well. Missing piece of the jigsaw puzzle? Only time will tell!!!

Monday, September 1, 2008

ADO.NET Data Services - Part 1

 

ADO.NET Data Services is a new feature that Microsoft has introduced as a part of the SP1 upgrade to .NET 3.5 and VS 2008. It was previously previewed as ASP.NET Extensions. But with the SP1 release a lot of things have changed around ADO.NET Data Services. Keep reading to find out more.

 

ADO.NET Data Services is exactly what it says. It exposes ADO.NET data as a set of Services. As an example if I have a customers table (as we do in Northwind database),  the table will be accessible by the URI http://myserver/data.svc/Customers. I can understand you already having thoughts about Security and Access Priviliges. Hold on, we will get to that in a brief while. But first things first, let us dissect ADO.NET Data Services further and see the “what” and “how”. We will then proceed to expose a sample database through ADO.NET Data Services and build a client to access the same.

 

ADO.NET Data Services has undergone quite a lot of changes in syntaxes and assemblies for the SP1 release from its preview. I will highlight those throughout this article.

 

The main purpose of ADO.NET Data Services is to expose data in a couple of new formats. Ie. JSON and ATOM. Most of you will be familiar with both of these formats. You can get more details about these formats at http://www.json.org/ and http://www.atomenabled.org/developers/syndication/atom-format-spec.php. The important thing to note here is that both ATOM and JSON are language independent formats thus enabling you to expose your data to a variety of clients. Representations of how data will be returned are given below.

 

ATOM

 

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>

<service xml:base="http://server/service.svc/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app">

<workspace>

  <atom:title>Default</atom:title>

  <collection href="Categories">

  <atom:title>Categories</atom:title>

  </collection>

  <collection href="CustomerDemographics">

  <atom:title>CustomerDemographics</atom:title>

  </collection>

  <collection href="Customers">

  <atom:title>Customers</atom:title>

  </collection>

  <collection href="Employees">

  <atom:title>Employees</atom:title>

  </collection>

   <collection href="Order_Details">

  <atom:title>Order_Details</atom:title>

  </collection>

  <collection href="Orders">

  <atom:title>Orders</atom:title>

  </collection>

  <collection href="Products">

  <atom:title>Products</atom:title>

  </collection>

  <collection href="Region">

  <atom:title>Region</atom:title>

  </collection>

  <collection href="Shippers">

  <atom:title>Shippers</atom:title>

  </collection>

  <collection href="Suppliers">

  <atom:title>Suppliers</atom:title>

  </collection>

  <collection href="Territories">

  <atom:title>Territories</atom:title>

  </collection>

  </workspace>

</service>

 

JSON

 


{

  "d" : {
     __metadata: {

        uri: "http://server/service.svc/Customers(\'ALFKI\')",

        type: "NorthwindModel.Customers"
     },

     CustomerID: "ALFKI",

     CompanyName: "Alfreds Futterkiste",

     ContactName: "Maria Anders",

     ContactTitle: "Sales Representative",

     Address: "Obere Str. 57",

     City: "Berlin",

     Region: null,

     PostalCode: "12209",

     Country: "Germany",

     Phone: "030-0074321",

     Fax: "030-0076545",

     Orders: {
        __deferred: {
           uri: "http://server/service.svc/Customers(\'ALFKI\')/Orders"
        }
     },

     CustomerDemographics: {
        __deferred: {
           uri: “http://server/service.svc/Customers(\'ALFKI\')/CustomerDemographics"
        }
     }
  }

}


 

 

The importance of exposing data in the JSON is more for AJAX enabled application. So if you built your site on Silverlight, for example, you can now get data in JSON format from your business services. This makes coding in Silverlight a lot more easier right? Further in this article, we will also do a quick comparison of using traditional methods and JSON formats.

 

ADO.NET Data Services use a style of software called Representation State Transfer (REST). In very simple terms, it means transferring data using HTTP without any messaging layer or formats. In ADO.NET Data Services, we will use HTTP GET, HTTP PUT HTTP POST and HTTP Delete for CRUD Operations. Yes. You read it right. You can now make updates and deletes over the web directly to your database. ADO. NET Data Services uses a data model called the Entity Data Model to represent data.

 

Addressing Scheme – GET OPERATIONS

 

We all know now that we can expose data as services with ADO.NET Data Services. But that still leaves a few questions unanswered. How do I maintain relationships? How do I sort and filter records?

 

Thankfully, the Data Services team has already thought about these questions. All of the above operations can be done using query strings and URIs.

 

Let us go back to the Customers example in the Northwind database. We saw that once they are exposed http://myserver/data.svc/Customers will give you access to the Customers table. Now to get hold of a particular record, all you have to do is to specify the entity key within parameters. So, http://myserver/data.svc/Customers(“ALFKI”) will now refer to a single entity. You can access the properties of the entity by using the property name after a “/”. That means, http://myserver/data.svc/Customers(“ALFKI”)/ContactName will give us access to the contact name of the customer. So far so good? Now let us move on. Another important aspect of any relational data is its association with other entities. In this case, a customer can have a list of orders against him. To access these associations, all you have to do is replace the property in the previous example by the name of the entity. http://myserver/data.svc/Customers(“ALFKI”)/Orders, in this case retrieves all the orders that the customer ALFKI is associated with. That is so cool!! But we are not done yet. We still have to see how to do filtering, sorting and paging, so lets get right into it.

 

 

Filtering, Sorting and Paging

 

Let us keep building on the example we already have. If  your requirement was to retrieve only the active orders for the Customer ALFKI you will change your URI to http://myserver/data.svc/Customers(’ALFKI’)/Orders?$filter=Active eq true. The URI uses filter=Active eq true to give you only active records on the Customer. There are other comparison operators you can use as well. 

 

Just like filtering you can also include query string options to order the resultset. For eg. http://myserver/data.svc/Customers(’ALFKI’)/Orders?$filter=Active eq true&$orderby=OrderDate orders the data by OrderDate.

 

Paging using Data Services is just a bit more complex than the other operations. Let me introduce to two new keywords “skip” and “top”. These keywords help you achieve paging of records with ADO.NET Data Services. Both skip and top take an integer value. “Skip” skips the number of records mentioned. For example skip = 30 will move you to the 31st record and “top” will restrict the number of records returned by the service. So top = 5 will mean that you get only 5 records. Use these two in conjunction and now you have paging implemented. So if I you need customers 20 to 30, you will add the skip and top options to the query string. The resultant URI now is http://myserver/data.svc/Customers?$skip=20&$top=10. You can use skip and top with Order By. If no order by is used, the resultset is ordered by the primary key in the table.

 

In general, the addressing scheme for ADO.NET Data Services can be depicted as http://host/vdir/<service>/<EntitySet>[(<Key>)[/<NavigationProperty>[(<Key>)/...]]]

 Where [] implies optional components.

 

Now that’s a lot for one reading. While you familiarize yourself with these concepts I will be back with the next step in this series that ponders on why anybody would use ADO.NET DATA SERVICES and the benefits of the same. Come back in about a week’s time for more.