Frank Wang's inspirations on .NET

IEnumerable<Inspiration> inspirations = from i in DataContext.Inspirations where i.Sharable == true select i

ADO.NET Entity Framework and Data Services in action(Part 3: Consuming ADO.NET Data Services)

Tuesday, March 11, 2008 2:07 AM

In Part 2 of this series, we created an ADO.NET Data Services that made the Northwind data available.

In today's blog post we are going to talk about how to consume the Northwind service. You can interact with an ADO.NET data service from any application that can send an HTTP request to an ADO.NET data service URI, and that can process the response in the format that is returned from the data service. To demonstrate this, we will create an ASP.NET web site to displayed the data retrieved from our Northwind data service.

Go ahead and create a new ASP.NET web site in Visual Studio 2008. Name the web site NorthwindWebClient. In order to use the client library to query data from data service, there're two things we need to do in the web site.

First of all, we need to be able to represent each of the entities defined in the data service as .NET objects in the client, corresponding classes need to be defined for the client application. Although you can always write your own "proxy" classes manually, the ASP.NET 3.5 Extensions Preview provides a nice command-line tool Webdatagen.exe as a better option. The Webdatagen.exe is located in directory \Program Files\Microsoft ASP.NET 3.5 Extensions. Launch the command prompt, changed to this directory, and then type in

WebDataGen.exe" /mode:ClientClassGeneration /outobjectlayer:northwind.cs /uri:http://localhost:51155/Northwind.svc

On my development machine, the Northwind Data Service is listening to port 51155 randomly assigned by the Cassini web server. Make sure you change it to your own port number in the command line. If the command executes successfully, you will see a new file northwind.cs created under \Program Files\Microsoft ASP.NET 3.5 Extensions.

Webdatagen

Copy northwind.cs to your app_code directory in the ASP.NET web site. Open this file in code editor, you will find the "NorthwindModel" namespace you already saw when you created the data service and the class name "NorthwindEntities". I think now you understand why this northwind.cs file is called "object layer file". It is going to serve as a proxy class for the data service in the client application.

/ Original file name: northwind.cs
// Generation date: 3/11/2008 12:04:51 AM
namespace NorthwindModel
{
    
    /// <summary>
    /// There are no comments for NorthwindEntities in the schema.
    /// </summary>
    public partial class NorthwindEntities : global::Microsoft.Data.WebClient.WebDataContext
    {
        /// <summary>
        /// Initialize a new NorthwindEntities object.
        /// </summary>
        public NorthwindEntities(string uriString) : 
                base(uriString)
        {
        }
        /// <summary>
        /// Initialize a new NorthwindEntities object.
        /// </summary>
        public NorthwindEntities(global::System.Uri baseUri) : 
                base(baseUri)
        {
        }

The second thing we need to do is reference the Microsoft.Data.WebClient, the client library that can return results as .NET objects and manage association traversal. It was shipped with the ASP.NET 3.5 Extensions Preview. Please note Microsoft.Data.WebClient  is NOT installed in the GAC, instead, it is in the directory C:\Program Files\Reference Assemblies\Microsoft\Framework\ASP.NET 3.5 Extensions. So go ahead and add this assembly to your project references. Make sure it is present in the web.config's <assemblies> section.

<assemblies>
                <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="Microsoft.Data.WebClient, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies>
        </compilation>

 

Now we are ready to query the data service and display the results in our web site. Add a ASPX page to the web site and name it EmployeeList.aspx. We are going to data bind all the Northwind employees to a grid view.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmployeeList.aspx.cs" Inherits="EmployeeList" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Employees</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>Northwind Employees</h2>
        <asp:GridView ID="gvEmployees" runat="server" CellPadding="4" 
            ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" >
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" />
                <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                <asp:BoundField DataField="Title" HeaderText="Title" />
                <asp:BoundField DataField="HireDate" HeaderText="Hire Date" />
            </Columns>
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

 

Switch to the code behind file for Employees.aspx. Add Micrsoft.Data.WebClient and NorthwindModel to the using directives, and then implement the data query in the Page_Load.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.Data.WebClient;
using NorthwindModel;
 
public partial class EmployeeList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebDataContext ctx = new WebDataContext("http://localhost:51155/Northwind.svc");
        WebDataQuery<Employees> employees = ctx.CreateQuery<Employees>("/Employees?orderby=LastName");
        gvEmployees.DataSource = employees;
        gvEmployees.DataBind();
    }
}

 

The query I wrote asks for all the Employee objects with sorting on the "LastName" field. Press F5 to run the web site.

Employees

Nice and easy, huh? Now let's go back to the Northwind Data Service one more time and take a look at the raw response for the that query. If you have been following this blog post so far, it should be still running on your development machine :-) Open a browser and enter URL http://localhost:51155/Northwind.svc/Employees?orderby=LastName

EmployeeRawResponse

Obviously, the client library Microsoft.Data.WebClient did all the hard work transforming AtomPub data to strongly typed objects defined in the NorthwindEntities.

By now, we have a ADO.NET data service and a working client application to retrieve and display the data. In the next blog post, we will be exploring the .NET client library for data service a little bit further by executing queries asynchronously. We will also alternatively query the WebDataContext using LINQ To Entities. You will see how the client library handles the details of mapping the LINQ statement to a URI in the target data service and retrieving the specified resources as .NET objects.



  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Feedback

No comments posted yet.


Post a comment