in Silverlight

Consuming ADO.NET Data Service (Astoria) from Silverlight

This post describes how to access the ADO.NET Data Service (Astoria) from Silverlight by using “ADO.NET Data Services Silverlight Add-On“.

Download : SourceCode

ADP.NET Data Service (Astoria) from Silverlight (Silverlight ListView)

Contents

  • Introduction
  • Prerequisites
  • Getting Started
  • SQL Database
  • Creating Web Application in Visual Studio 20008
  • Creating ADO.NET Entity Data Model
  • Creating ADO.NET Data Service
  • Silverlight ListView
  • Conclusion

Introduction

This article is just an introduction of how to use Astoria in Silverlight application. The sample that I used in this article is nearly as same as the sample which is mentioned in ASP.NET 3.5 Extensions Preview (Quick Start). But I used the Astoria Silverlight Addon and create the Silverlight listview that looks cool.

Background

Project Astoria Team released ADO.NET Data Service library for Silverlight on 11st January, 2008. This is very interesting news for Silverlight developer. I was thinking to give a try when I heard that news but a lot of things keep me busy until 15th of Jan. Now, I got a chance to try and make this sample for you all. I hope you guys like it.

Prerequisites

You need to install the following installers in order to use Astoria Service, Silverlight.

Getting Started

After installing all required installers, you started creating new project to give a try how to use ADO.NET Data Service in Silverlight application. Like my other articles, I will give you the step-by-step details on how to consume Astoria in Silverlight. If you are not clear something, please just drop a comment in this post. I will get back to you as soon as I can.

SQL Database

You need to create one database that can be used in our sample. (If you already download the sample, you can find the SQL database called EmployeeMgmt.mdf in zip file.) If you want to create your own database, open SQL 2005 management studio and create new database. Then, create new table and fill some data in that table. (As this article is not for creating the database in SQL, I won’t go step by step. If you have some problems in doing this, please let me know.)

Creating Web Application in Visual Studio 20008

After creating the database, we will start creating new ASP.NET web application in Visual Studio 2008.

  • Click “New Project” icon or Press “Ctrl+Shift+N”
  • Select “ASP.NET Web Application” and name the application as “ADO.NETSrv”
  • Click “OK” button
  • Go to the properties of “ASP.NET Web Application”
  • Select “Web” tab
  • Select “Specific” port as the screenshot below (Visual Studio uses the dynamic port for ASP.NET by default. But using the dynamic port will give us the trouble “Cross-domain issue” since we are going to hard-code the service URL in our silverlight project. So, we just make sure our site to run with static port.)Making the static port in Visual Studio 2008

This is about creating ASP.NET web application in Visual Studio 2008. We will create “ADO.NET Entity Data Model” in next step.

Creating ADO.NET Entity Data Model

  • Add new item “ADO.NET Entity Data Model” to our web application
    ADO.NET Entity Data Model
  • Click “OK” button (Entity Data Model Wizard will be shown as the picture below).
  • Select “Generate from Database”Model Generate from Database
  • Click “Next” button
  • Choose Your Data ConnectionChoose Your Data Connection
  • Click “Next” button
  • You have to choose your table in that step. (Customer table in my case)
    Choose Your Database Objects
  • Click “Finish” button (Visual Studio will create Model1.edmx in your project.)
    Customers Table

That’s all about creating “ADO.NET Entity Data Model” in Visual Studio 2008. We will create “ADO.NET Data Service” in next step.

Creating ADO.NET Data Service

  • Add “ADO.NET Data Service” to your web application (Note : If you don’t have ASP.NET 3.5 extension installed in your machine, you won’t see this template.)ADO.NET Data Service
  • Click “Add” button
  • Open “WebDataService1.svc.cs” file. ( You will see “WebDataService< /* TODO: put your data source class name here */ >” in WebDataService1 class.)
  • Write your data source class name in that place. ( WebDataService<EmployeeMgmtEntities> in my case.) If you don’t see the class in your intellisense, add your data model namespace (e.g. using EmployeeMgmtModel;) in that class. (if you don’t know what your data model namespace, you can check it in “Model Browser” )
  • Write the following code in InitializeService method
    config.SetResourceContainerAccessRule("*", ResourceContainerRights.All);
    

That’s all about creating ADO.NET Data Service in Visual Studio. You can run the project now. It will show you like Feed. So, if you want to see the XML, you need to disable the “Feed Reading View”. Go to “Internet Options”>Content>Feeds Setting. Uncheck “Turn on feed reading view”.

“Turn on feed reading view”.

Then, you can run the application. You will see the data as XML format in browser. You can query the data from url like http://localhost:49970/WebDataService1.svc/Customers or http://localhost:49970/WebDataService1.svc/Customers(1001)/ in address bar. (1001 is the id of first customer.) This is one cool thing about ADO.NET Data service. If you want to know more about this query, you can read here. Okay!!. We will create the Silverlight project in next step.

Creating Silverlight project with ADO.NET Data Service Silverlight Addon

  • Add the Silverlight project to your solution
  • Add “Microsoft.Data.WebClient.dll” as a reference in your silverlight project
  • Add the SilverlightLink to Web applicationAdd Silverlight Link
  • Copy TestPage.html, TestPage.html.js and Silverlight.js to Web Application
  • Set TestPage.html as a startup page
  • Create the class like below. (Note: The class name should be the same as your table name. The fields should be the same as your table structure.)
    public class Customer {
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    }
    

    I don’t like to create that class in Silverlight project but this is by-design issues so that I have no choice. I hope Astoria Team will do something about it.

  • Write the following code in Page_Load event to invoke the ADO.NET Data Service from Silverlight
    try {
    WebDataContext ctx = new
    WebDataContext("http://localhost:50527/WebDataService1.svc");WebDataQuery<Customer> customers = ctx.CreateQuery<Customer>("/Customers?$orderby=CustomerID");
    
    foreach (Customer c in customers) {
    Console.WriteLine(c.CustomerID + "," + c.CustomerName);
    }
    }
    catch (Exception ex) {
    Console.WriteLine(ex.Message);
    }
    

You can set the breakpoint in foreach loop and run the application. You will get all records from your database. but how we can show the data in Silverlight?

Silverlight ListView

There is no Gridview or ListView in Silverlight application. So, we have to create our own control for that. Based on the design of Microsoft Download Beta, I have created one simple Silverlight ListView to show the data in Silverlight application.

Let’s try to check how our listview looks like. We have to comment all codes in Page Load event and write the following code to show the ListView. Then, run the application.

ListView _listview = new ListView();
_listview.Items.Add(new ListViewItem("", ""));
_listview.Items.Add(new ListViewItem("", ""));
_listview.Items.Add(new ListViewItem("", ""));
_listview.Items.Add(new ListViewItem("", ""));
_listview.UpdateView();
this.Children.Add(_listview);

Great! our listview looks cool.

Silverlight ListView

then, update the code like below in Page load event. And run the application. All records from Database will be shown in our ListView through ADO.NET Data Service.


try {

WebDataContext ctx = new
WebDataContext("http://localhost:50527/WebDataService1.svc");

ListView _listview = new ListView();

WebDataQuery<Customer> customers = ctx.CreateQuery<Customer>("/Customers?$orderby=CustomerID");

foreach (Customer c in customers) {
Console.WriteLine(c.CustomerID + "," + c.CustomerName);
_listview.Items.Add(new ListViewItem(c.CustomerID.ToString(), c.CustomerName));
}

_listview.UpdateView();

this.Children.Add(_listview);

That’s all about consuming the ADO.NET Data Service from Silverlight application. Even though this article doesn’t cover any details about ADO.NET Data Service, I hope you will get some understanding about how to use that service in Silverlight application. This is the purpose of writing this article. Hopefully, you enjoy reading it. Feel free to drop a comment if you have any suggestion or comment. Thanks.

Related ~

Leave a Reply

23 Comments

  1. Dear Michael

    Sure! Thanks for reminding me. I gave the permalink of your post about iGoogle themes. Please check the link to see if it is satisfactory.

    Best,
    Roja

  2. Hey Michael; Thanks for great step-by-step; I guess next, we have to figure out how to do the CRUD operations!

  3. Hi Ben,

    :) I was trying to do CRUD sample last week. The problem is that there is no textbox control that I can use in silverlight project. I don’t want to use ASP.NET textbox.. so, i tried using Liquid controls 2.2 and GOA controls. but those controls are missing a lot of features. Another thing that I dont like about GOA controls is that we have to change a lot of ways to write SL application in order to use that control..

  4. Hi Michael,

    Very nice quickstart.

    Quick question about the way you’re accessing ADO.Net DataServices.
    1. Do you think that a loosely typed URL based access is the best way to access ADO.Net Dataserves from Silverlight?
    IMHO, the following line is extremely fragile:
    WebDataContext ctx = new
    WebDataContext(“http://localhost:50527/WebDataService1.svc”);
    WebDataQuery customers = ctx.CreateQuery(“/Customers?$orderby=CustomerID”);
    There’s a hard coded server address, hard-coded service name, loosely typed and hard-coded type name and a loosely-typed and hard-coded property name.

    2. You did a slide of hands by copying the “Customer” class to the Silverlight app. In a real-world app do you think developers can realistically copy classes back and forth between two projects?

  5. Hi Justin,

    1.

    Yes. You are right about that. I’m also looking for the way to do something more flexible.

    2.

    Bryant pointed me the easier way to do this. (You can get the link from trackback URL.) We can use “Webdatagen.exe” tool to generate the proxy class for that. There will be one class in the web project and another one as a proxy class in Silverlight project.. but this is the same as the way that we use WebService Proxy in ASP.NET…

  6. How would I go about solving this?

    The member with identity ‘EmployeeMgmtModel.Customers’ does not exist in the MetadataCollection.
    Parameter name: identity
    at System.Data.Metadata.Edm.ItemCollection.GetItem[T](String identity, Boolean ignoreCase)
    at System.Data.Metadata.Edm.MetadataWorkspace.GetItem[T](String identity, DataSpace dataSpace)
    at Microsoft.Data.Web.Providers.ObjectContextServiceProvider.GetClrTypeForCSpaceType(MetadataWorkspace workspace, ObjectItemCollection objects, EdmType type)
    at Microsoft.Data.Web.Providers.ObjectContextServiceProvider.PopulateMetadata(Dictionary`2 knownTypes, Dictionary`2 entitySets)
    at Microsoft.Data.Web.Providers.BaseServiceProvider.PopulateMetadata()
    at Microsoft.Data.Web.WebDataService`1.CreateProvider(Type dataServiceType)
    at Microsoft.Data.Web.WebDataService`1.CreateProviderForRequest()
    at Microsoft.Data.Web.WebDataService`1.ProcessIncomingRequest()

  7. Hello TFisher,

    How would I go about solving this?

    Could you please give me more information about your problem? Are you getting this error from the sample that I attached in this article? If yes, have you installed all installers that I mentioned in this post? seems like you missed to install something in your machine..

    If no, what are you trying to do and how did you get this error?

  8. Hi, thanks Michael for this article.

    I’ve some questions and.. problem

    [0]
    Sorry in advance for my low english :D

    [1] problem
    I’ve try this quickstart and when I run the project I have a blank page (nothing appears, no listview, no textblock), so I’ve try your source project and I had the the same empty page when running it. I put a breakpoint on the “foreach Customer” but VS never stops on this breakpoint (I’ve checked the Silverlight option on the web tab of project properties)

    Can you help me ?

    [2] question
    If we have several tables on our database, what is the best way between creating an Entity Data Model foreach table (or a tables group) or only one EDM for all tables of the database ? For example if I have a database with “News” with a relation on “Users” with a relation on “Roles” and a table “Products” with a realtion on “Uers”, is it better to do an EDM with news-users-roles and another with users-products or one EDM with all tables ?

    [3] question
    We can use LINQ with the DataService.svc, do you think is better using LINQ or URI to get data (in a read and write system) ?

    One more time thanks for this nice job.

  9. Sorry for the preceding message (“Did you delete my comment ?”), I’ve posted it on the wrong forum…

    Ok it works with a TextBlock but it’s very strange because I’ve try this morning and it didn’t work, I try it now and it workds, I didnt change anything…

    With your ListView I have the following error :
    Value cannot be null.
    Parameter name: stream

    With the TextBlock it works but only on IE, on firefox I get the following error:
    System does not support ‘iso-8859-1′ encoding. Line 1, position 31.

    I’ve try to change the encodage option but no success.

  10. [0]
    Sorry in advance for my low english

    No problem. I’m not a native english speaker either. :)

    [1] problem
    I’ve try this quickstart and when I run the project I have a blank page (nothing appears, no listview, no textblock), so I’ve try your source project and I had the the same empty page when running it. I put a breakpoint on the “foreach Customer” but VS never stops on this breakpoint (I’ve checked the Silverlight option on the web tab of project properties)

    Can you help me ?

    Which version of Silverlight did you install on your machine? You should install Silverlight 1.1 Alpha runtime, Silverlight 1.1 Alpha SDK and Silverlight 1.1 Alpha Tool for Visual Studio 2008. Make sure that you have close all web browers while installing.

    [2] question
    If we have several tables on our database, what is the best way between creating an Entity Data Model foreach table (or a tables group) or only one EDM for all tables of the database ? For example if I have a database with “News” with a relation on “Users” with a relation on “Roles” and a table “Products” with a realtion on “Uers”, is it better to do an EDM with news-users-roles and another with users-products or one EDM with all tables ?

    You should create only one EDM for all tables. No need to create EDM for each table.

    [3] question
    We can use LINQ with the DataService.svc, do you think is better using LINQ or URI to get data (in a read and write system) ?

    There are a few bugs in Astoria. it doesn’t work well with all LINQ scenerios.

    What do you mean by “(in a read and write system)” ? you mean, Database operations? Please check-out this article “CRUD operations in Siverlight using ADO.NET Data Service

    Hope it helps.

  11. Ok Michael the CRUD’s article seems like what I want to know.

    I’m learning Silverlight for my dissertation (ended in June), I will have to work on the beta version released in March, which is not easy to find the proper documentation, thank you for your articles, it’s very useful.

  12. hi,Michael
    I have no idea why it’s nothing to do when I click “New Connection” button choosed my data connection.
    By the way,I already installed all of requisite software.

  13. I have no idea why it’s nothing to do when I click “New Connection” button choosed my data connection.

    Do you have SQL 2005 express or server installed in your machine?

    btw, which version of Silverlight are you using? This sample is for SL 1.1 (2) alpha. If you are using Silverlight 2 beta1, it won’t work. Astoria client for SL doesn’t currently work with SL2beta1. you hav to use WebHttpRequest and invoke the service manually.

  14. Yeah,I use Silverlight 2 beta1 indeed.ok,Thanks a lot!
    If I want to operate database in Silverlight2,I have to do like your “article:Silverlight 2 (beta1) – Database Operations with ASP.NET Web Service in Silverlight 2″

  15. What is not supported by SL 2.0 Beta? The client in general?

    In which case, can we expect this anytime soon? We are dying to consume ADO.Net service in Silverlight, but doing it manually without the context… seems to remove much of the inherent benefit.

  16. Hi Micheal,

    Looks great, I’m surprised how easy silverlight is when you know WPF. I do have a question however, is there a way to get the URI for the data service from some kind of configuration source that is deployed with the silverlight application?

    Thanks in advance,

    Willem Meints

  17. Hi Willem,

    AFAIK, the current version of Silverlight doesn’t support the client config file. However, you can always use the XML file for storing the configurations and download it on demand.

  18. hi, how can we tell the DataServiceQuery failed or not? normally with wcf, we can tell it by e.Error, and no need to trap the exception by ourselves. but with DataServiceQuery, there is no e.Error, and seems that we need to handle the exceptions.

  19. Hi,

    How do I get JSON response from ADO.NET Data Services service from silverlight application? I am not able to change the header to tell I want JSON back instead of feed xml. Do you have a sample for this?

    Thanks.