Skip to content

Silverlight 2 beta 2 LOB applications

I’m pretty often asked the question “Can I use real (as in coming from a database) data in my Silverlight application?” the answer is “of course”, although this requires a lit more work than any other technology (WinForms, ASP.NET, WPF) you could use. The reason for that is, that as you probably already know, Silverlight runs on the client, so you’ll need a way to move the data from the server to the Silverlight Client application.

There are a number of ways you can achieve that, like for example building a WCF Service and the necessary DTOs (Data Transfer Objects) to communicate between Silverlight and your Business Layer. There is though, a far more easiest way to achieve that functionality and that is using .

For those that haven’t heard about ADO.NET Data Services before, ADO.NET Data Services is a new part of the .NET 3.5 framework that supports exposing a data model (e.g. LINQ for SQL, Entity Framework, etc.) as a set of queryable REST endpoints. ADO.NET Data Services maps the four data verbs into the four HTTP verbs POST (Create), GET (Read), PUT (Update), DELETE (Delete).

Essentially it provides a way to use a data model across the firewall. It works by exposing IQueryable endpoints through a URI-based syntax allowing developers control over how the data is retrieved. In addition ADO.NET Data Services utilizes JSON and Atom as the serialization formats. These make it easy to consume in client-side interfaces like Silverlight and AJAX.

In order to use ADO.NET Data Services you’ll first have to create a Data Model. You can either use a Linq To SQL (it currently supports only read – you’ll have to implement updates) or an Entity Framework model. Once your data model is ready you can create a new Data Service in your Silverlight Web Site (Note: the data service won’t work if it’s implemented in a different domain than the one running the Silverlight application. Cross domain calls are disabled due to IE security) by right clicking on your project and selecting “add new ADO.NET Data Service”. Once the service is created you’ll have to specify the model type in the service code behind as well as the permissions the service will have on the data.

public class WebDataService : DataService< /* TODO: put your data source class name here */ >
{
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(IDataServiceConfiguration config)
    {
        // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
        // Examples:
        // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);
        // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
    }
}

The next step is to create the service proxy classes in your Silverlight project. You can do that either by adding a service reference to your Silverlight application project or by using the DataSvcUtil.exe tool located in the C:WindowsMicrosoft.NETFrameworkv3.5 directory to create them and then copy them to your project. Typically you would call it by specifying the URI of the service, the name of the class file to create and what language to use:

DataSvcUtil.exe /uri:http://localhost:1025/YourService.svc
                /out:dataclass.cs
                /language:CSharp

You will also need to add a reference to the System.Data.Client.Services.dll assembly. This is the ADO.NET Data Services client library that allows asynchronous LINQ queries that are translated into the URI syntax automatically. Note that if you’ve installed Visual Studio 2008 SP1 this library is no longer compatible with ADO.NET Data Services and you’ll not be able to connect to your service. (read more about this here). Fortunately the guys in Microsoft have released an interim version of this assembly that works with Silverlight Beta 2 until Silverlight releases its next version. You can download this assembly from Mike Flasko’s blog.

The way you work with the referenced service is similar to the way you would normally work with an Entity Frameworrk Data model. You first instantiate a Data Context specifying the service URI and then you create a Linq query to fetch the data. Now normally, you could execute the query directly by calling something like ToList() against the query, that isn’t supported in Silverlight 2 Beta 2 though.  In fact, if you try you will simply get a NotImplemented exception. In order to execute these queries, you will need to cast the query into a DataServiceQuery.  The DataServiceQuery allows you to call BeginExecute to start an asynchronous query as seen below:

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
 
  NorthwindEntities ctx = 
    new NorthwindEntities(new Uri("/Products.svc", UriKind.Relative));
 
  var qry = from p in ctx.Products
             orderby p.ProductName
             select p;
  
  // Cast the query to a DataServiceQuery
  DataServiceQuery<Product> productQuery = 
    (DataServiceQuery<Product>)qry;
 
  // Start the execution
  productQuery.BeginExecute(new AsyncCallback(OnLoadComplete), 
    productQuery);
}
 
void OnLoadComplete(IAsyncResult result)
{
  // Get a reference to the Query
  DataServiceQuery<Product> productQuery = 
    (DataServiceQuery<Product>)result.AsyncState;
 
  // Get ther esults and add them to the collection
  List<Product> products = productQuery.EndExecute(result).ToList();
}

Once the query completes, it will call the OnLoadComplete method that was specified in the AsyncCallback.  In this method, you first grab the DataServiceQuery that you sent with the request then end the execution to retrieve the results.

While its not as straightforward as synchronous execution, the new ADO.NET Data Services certainly works well in Silverlight 2 Beta 2 and provides a great way to use existing or planned data models over Internet applications.

Published inADO.NET Data ServicesSilverlight

One Comment

  1. You certainly have some agreeable opinions and views. Your blog provides a fresh look at the subject. Thanks for spending the time to discuss this. I believe your forthcoming articles will turn out to be just as helpful.

Leave a Reply

Your email address will not be published.