Tuesday, September 16, 2008

ADO.NET Data Services - Part - III

To work with ADO.NET Data Services, you should ensure that you have .NET 3.5 Framework SP1 installed. Apart from ADO.NET Data Services SP1 brings to the table a lot of new features. For a list of new features in SP1 refer to this link (VS 2008 and .NET 3.5 SP1 Features).


Once you have the SP1 installed, open VS 2008 and open a new web application. Right click on the solution and add a new ADO.NET Data Entity model. The extension of the file will be edmx. A wizard will guide you through the process of creating an entity model based on a selected database. I will not get into the details of the wizard for the sake of brevity. The wizard is quite self-explanatory. The only thing worth mentioning is to set support for MARS resultsets in your advanced window when you click new connection.



Once you have run through the wizard, depending on the tables you have selected you will see a data model like the one shown in the picture.


You can also create an entity model only for the tables you want, by selecting the appropriate tables in the wizard. We will now go on to add the ADO.NET Data Service. You can do this by opening  the add new item dialog box and selecting ADO.NET Data Service from it.


Once you have added the svc, you will see the code behind. Lets take a look at the only method that exists.


The method InitializeService is the first method that will be called when your service is invoked.  Any code that you write in this method is applicable to all the data models that you expose through your web service. One of the key things that you will do here is taking care of security. Though .NET gives us some built-in methods to set rights, more often than not we will be writing our code to monitor these accesses. The InitializeService gives us a single place where we can write code for access privileges for the whole service.


Coming back to the code behind, there are a couple of things you have to change in here to get it up and working. You will have to include the name of the datasource class in your servce name declaration. Replace the “/* TODO: put your data source class name here */ with the name of your entity class. You can find out the name of the entity class by looking the class name from the designer.cs file.


Build and run the solution. You will get a response like the one shown in the picture. This is because currently you have not set the rights. To view or access the exposed services, you should give rights explicitly.



Open your code editor. In your InitializeMethod uncomment the two statements


config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);

config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);


Replace the “MyEntitySet” with the name of the Entity and “MyServiceOPeration” with the name of the operation or the methods that you write. To provide access to all the entities and the operations use “*”. In my code for testing, this is what I have done.


             config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);

             config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);


That’s it!! Your service is now ready to be accessed. Build and run the solution again. You will see something like below. Look at how the results have changed just by including those two lines in the InitializeService method.



One thing I would like you to note is the format of the data. In the above example, data is being returned as ATOM feeds.


Now that we have built a service, we next have to build a client to access this service. More of that in the next part. Happy Coding!!!

Saturday, September 13, 2008

This is Anfield!!!!

How long does it take to travel from Cloud nine to Earth? If you ask Sir Alex this question, his answer would be 90 minutes. Because that’s exactly what Man Utd. Went through on their trip to Liverpool. Rafa had a day to savour as he won his first victory against Manchester United 2-1.


The start was anything but uneventful. The starting line-ups were pre-cursors to what was to follow. No Gerrard; No Torres for Liverpool and Ferguson sent out a statement of “intent” by playing Berbatov in the starting line-up. For the first 20 minutes everything seemed to go United’s way. Berbatov was involved in the build up on the right hand side to what would eventually be a Carlos Tevez goal. Tevez had another chance when he had to net in a cross with Just Reina to beat but he couldn’t keep it down. Tevez and United eventually paid heavily for that miss because as it turned out Liverpool just arrived into the game late. When they did, they swept away the “Red Devils”. For the next 70 minutes only one team played.


There were the likes of Rooney, Tevez, Berbatov, Kuyt and Keane on the pitch but the irony was all the three goals were scored due to big defensive lapses. Javier Masceranho was the first culprit for not tracking Tevez’s run into the middle.Unmarked Tevez netted Berbatov’s cross in the 3rd minute to give United the lead. Most of Liverpool’s attacking was from the right, with Arbeloa and debutant Riera being impressive. In the 26th minute, Van Der Saar messed up a Liverpool cross to fumble the ball to Wes Brown’s feet resulting in an own goal. Liverpool were level. As hard as United tried, it wasn’t just their day. Carrick was making his comeback from an injury but that didn’t last long. He injured himself on a sliding tackle trying to win the ball back. A substitution was apparent and Liverpool were getting on top.


Second half continued to be more embarrassment for the visitors. Ryan Giggs came in for Carrick. It seemed as if the substitution would work when his long distance drive was on target making Reina stretch to keep it out. As it turned out that wouldn’t be Giggs most significant moment in the game. Liverpool were keeping up the pressure at the other end. Rafa brought in Gerrard and Babel to induce some pace into the Liverpool attack. In the 75th minute, Giggs, riding the baseline, instead of kicking the ball over for a corner, tried to keep it in play only for Liverpool to take possession. Kuyt’s cross met Babel’s legs resulting in the winner for Liverpool. But the trauma for United was far from over. A minute before full time, Vidic made an error in judgement hustling for a ball he was never in contention for. He was given a second yellow and a red. He will now miss his game against Chelsea.


The victory now leaves Liverpool top of the table but Chelsea can catch them when they play Manchester City later in the day. As for United, 4 points from the first 3 games is hardly the start they would have liked. They are not strangers to having slow starts and catching up during the latter half of the season, so don’t write them off just yet. But for their striker trio, I don’t think we will see Berbatov, Rooney and Tevez starting again for some time.

Thursday, September 11, 2008

Who's Who - I

  • Whose "About Me" reads "Okay, here goes: twenty-something, single, female, writer, with large groups of friends and who goes out for drinks pretty regularly. That's my life and that's what I write about. Okay? Okay."


  • X's company was taken away from him when he was 30. He resigned and founded his own company Y. One year after he was sacked, he acquired the company Z from W. Y was then bought out by his original company A. X is now the CEO of A. Identify all the variables.


  • He is the 5th genration descendant of the legendary warrior Sardar Hari Singh Nalwa. His parents are the promoters of Hitech Group of Companies. Identify this personality who is a household name now.


  • At the London Film Festival when Y was bowing accept the audience's appreciation, he was informed that a very important celebrity wanted to meet him backstage. Y was stunned to find Z waiting to hug him and congratulate him. Identify the two personalities in question here


  • Identify this person. A bonus for explaining what he is credited with.







    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";




    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








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


      <content type="application/xml">

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




    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.




    <?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">



      <collection href="Categories">



      <collection href="CustomerDemographics">



      <collection href="Customers">



      <collection href="Employees">



       <collection href="Order_Details">



      <collection href="Orders">



      <collection href="Products">



      <collection href="Region">



      <collection href="Shippers">



      <collection href="Suppliers">



      <collection href="Territories">









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