Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
LeftbarAd
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Silverlight » Silverlight 2 use ADO.NET Data Services to access data

Silverlight 2 use ADO.NET Data Services to access data

In this article will show how to perform CRUD (Create, Retrieve, Update, Delete) operations in Silverlight 2 using ADO.NET Data Services.

Author Rank:
Technologies: ASP.NET 3.5, Silverlight, XAML,Visual C# .NET
Total downloads : 223
Total page views :  10238
Rating :
 2.5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SilverlightApplication6.zip
 
ArticleAd
Become a Sponsor



Silverlight 2 has the ability to consume ADO.NET Data Services from within Silverlight projects. ADO.NET Data Services are a perfect match for client-side technologies like Silverlight and ASP.NET AJAX.

The ADO.NET Data Services framework consists of a combination of patterns and libraries that enable the creation and consumption of data services for the web. Its goal is to facilitate the creation of flexible data services that are integrated with the web, using URIs to point to pieces of data and simple, well-known formats to represent that data, such as JSON and plain XML.  This results in the data service being surfaced to the web as a REST-style resource collection that is addressable with URIs and that agents can interact with using the usual HTTP verbs such as GET, POST or DELETE. ADO.NET Data Services models the data exposed through the data service using an Entity-Relationship derivative called Entity Data Model (EDM). This organizes the data in the form of instances of "entity types", or "entities", and the associations between them.

In Silverlight 2 ADO.NET Data Services is composed of in-memory library allows asynchronous LINQ queries that are translated into the URI syntax automatically.ADO.NET Data Services maps the four data verbs into the four HTTP verbs:
Create == POST
Read == GET
Update == PUT
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 through Filtering, Sorting and Paging.

Prerequisites
Install the following in order to use ADO.NET Data Services with Silverlight.

Create a Silverlight application in visual studio 2008

Creating ADO.NET Entity Data Model

  1. Add new item ADO.NET Entity Data Model to App_Code folder of Web Application
  2. In Entity Data Model Wizard select Generate from Database
  3. Select a data Connection or create new connection
  4. Choose database objects
  5. Model.edmx will be like below

Creating ADO.NET Data Service

  1. Add ADO.NET Data Service to the Web Application
  2. Open WebDataService.cs and update the line
    public class WebDataService : DataService< /* TODO: put your data source class name here */ >
    with
    public class WebDataService : DataService< TestModel.TestEntities >
  3. Set the operation rules and access rules in InitializeService
    public static void InitializeService(IDataServiceConfiguration config)

    {

        // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.

        // For testing purposes use "*" to indicate all entity sets/service operations.

        // "*" should NOT be used in production systems.

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

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

}

  1. Run the Service and results will be as below
  2. And if use the database object name then the respective records are displayed

Create ADO.NET Data Service Proxy for Silverlight Project

  1. Open command prompt and navigate to C:\WINDOWS\Microsoft.NET\Framework\v3.5 folder. Type the following command
    DataSvcUtil.exe /out:Proxy.cs /uri:http://localhost:26031/silverlightApplication6Web/WebDataService.svc

    Here Proxy.cs is the name of proxy file to be genarated and http://localhost:26031/silverlightApplication6Web/WebDataService.svc is the URL of ADO.NET Data Service.
  2. The resulting screen
  3. Check the Proxy.cs under C:\Windows\Microsoft.NET\Framework\v3.5 and add this proxy file to Silverlight project. Add a reference for ADO.Net Data Services assembly System.Data.Services.Client.dll (formerly called Microsoft.Data.WebClient.dll).

Retrieving the record from Database in Silverlight

  1. Create a datagrid in Page.xaml
    <Grid x:Name="LayoutRoot" Background="White">

        <Grid.RowDefinitions>

            <RowDefinition Height="8*" />

            <RowDefinition />

            <RowDefinition />

        </Grid.RowDefinitions>

        <my:DataGrid x:Name="dataGrid" Margin="10" AutoGenerateColumns="True" AutoGeneratingColumn="OnGeneratedColumn"/>

        <StackPanel Grid.Row="1" Orientation="Horizontal">

            <Button x:Name="ButtonSelect" Margin="10" Content="Get Data" Click="ButtonSelect_Click" />

        </StackPanel>

</Grid>

  1. Create the Button Click event to retrieve data from database
    /// <summary>

        /// Handles the click event of ButtonSelect

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void ButtonSelect_Click(object sender, RoutedEventArgs e)

        {

        //1. Using the untyped approach using DataServiceContext

            //DataServiceContext proxy = new DataServiceContext(new Uri("WebDataService.svc", UriKind.Relative));

            //var query = proxy.CreateQuery<Users>("Users?orderby=UserID");

       

        //2. Using the generated class that inherits from DataServiceContext

            TestEntities proxy = new TestEntities(new Uri("WebDataService.svc", UriKind.Relative));

            //var query = proxy.Users.OrderBy(u => u.FirstName);

            //create more comples query

            //var query = proxy.Users.OrderBy(u => u.FirstName).Skip(1).Take(5);

            //var query = proxy.Users.Where(u => u.UserID == 1);

 

        //3. Using LINQ to ADO.Net Data Services

            var query = (from u in proxy.Users where u.UserID > 0 orderby u.LastName descending select u);

 

            // Cast the query to a DataServiceQuery

            DataServiceQuery<Users> userQuery = (DataServiceQuery<Users>)query;

            userQuery.BeginExecute(new AsyncCallback(OnLoadComplete), query);

}
/// <summary>

        /// AsyncCallback to the BeginExecute

        /// </summary>

        /// <param name="result"></param>

        void OnLoadComplete(IAsyncResult result)

        {

            // Get a reference to the Query

            DataServiceQuery<Users> query = (DataServiceQuery<Users>)result.AsyncState;

            // Get the results and add them to the collection

            // List<Users> Users = query.EndExecute(result).ToList();

            // or Get the results and add them to datagrid

            dataGrid.ItemsSource = query.EndExecute(result).ToList();

 }

That's all you are done. Run the code and you will see the result. I will discuss the Insert,Update and Delete Operations in next article.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Nipun Tomar
Nipun has 5 years working experience in .NET technologies. He holds Bachelor's and Master's degree in Computer Science. Currently working on ASP.NET 2.0/3.5, VB.NET, C#.NET, AJAX, SQL Server 2005, WPF, WCF and Silverlight.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SilverlightApplication6.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Service Pack 1 release vs2008 August 11thFrank8/27/2008
are there ado updates that will change or allow you a different approach?
Reply | Email | Delete | Modify | 
Service Pack 1 release vs2008 August 11thFrank8/27/2008
are there ado updates that will change or allow you a different approach?
Reply | Email | Delete | Modify | 
Proxy vs Add Service ReferenceFrank9/15/2008
the ado folks want us to use service references.. the proxy doesn't generate.. could you publish a version of your excellent July 19 article using a service reference .. or an update example .. all of the ado artices on the next are, to me, very very way over complicated .. i just want to get in and out of the sql database using silverlight. Thanks! frankp414@gmail.com
Reply | Email | Delete | Modify | 
 
 
Re: Proxy vs Add Service ReferenceNipun9/23/2008

are you looking for this?

Data Access in Silverlight Controls using Silverlight Enabled WCF Service

Data Access and Data Binding in Silverlight Controls using WCF Service

Reply | Email | Delete | Modify | 
Test commentNipun9/24/2008
Test comment
Reply | Email | Delete | Modify | 
STRUGGLIN!Vusa10/28/2008
Nipun, I have been trying to get your example to work on my computer for a couple of days now.I get an "An error occurred while processing this request" when i step through my code to the "dataGrid.ItemsSource = query.EndExecute(result).ToList();" line. How did you get your code to work yet there are some people who are claiming that there are know compatibity problems between silverlight and Ado.net Data services??...SOS , please help. Vusa
Reply | Email | Delete | Modify | 
Solution for consuming ADO.NET services with SilverLightJoseph Britto5/28/2009
 

public Page()
{

InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);

}

void Page_Loaded(object sender, RoutedEventArgs e)

{

Uri uri = new Uri(HtmlPage.Document.DocumentUri, "NorthwindDataService1.svc");

NorthwindEntities context = new NorthwindEntities(uri);

var query = from cust in context.CustomerSet

select cust;

var dsQuery = (DataServiceQuery<customer>)query;

dsQuery.BeginExecute(

result => dgCustomers.ItemsSource = dsQuery.EndExecute(result),

null);
}

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved