Silverlight 2 series (17): Data and communication-ADO. NET Data Services

Source: Internet
Author: User
Overview

The release of Silverlight 2 Beta 1 brings us a lot of surprises from Runtime and Tools, such as supporting the framework languages Visual Basic, Visual C #, IronRuby, Ironpython, A series of new features such as JSON, Web Service, WCF, and Sockets support. The article "one-step learning Silverlight 2 series" takes you to Silverlight 2 development quickly from the following aspects: Silverlight 2 basic knowledge, data and communication, custom controls, animation, and graphic images.

This article briefly introduces how to call ADO. NET Data Services in Silverlight 2.

Prerequisites

Since ADO. NET Data Services is in ASP. NET 3.5 Extensions, before starting this example, you must install the latest version of ASP. NET 3.5 Extensions. You can download it from here. After the installation is complete, you can see the ADO. NET Data Service items in the Add new project dialog box:

ADO. NET Data Service allows applications to publish Data in the form of services, so that we can directly access Data through a browser. It supports open industry standards such as AtomPub and JSON. It supports standard HTTP actions such as POST, GET, PUT, and DELETE to create, update, DELETE, and read data. More information about ADO. NET Data Service is provided here. You can view relevant information.

Simple Example

If you read the previous three articles, you may be annoyed with the following interface, but I will still use this example to demonstrate it in this article :)

After the Silverlight 2 project is created, we add a Post class in the Web project:

public class Post{    public int Id { get; set; }    public string Title { get; set; }    public string Author { get; set; }}

We use Id as the primary key of Post. data. web. dll Assembly Reference, located in <drive letter> \ Program Files \ Reference Assemblies \ Microsoft \ Framework \ ASP.. NET 3.5 Extensions introduces the namespace using Microsoft. data. web, and add the [DataWebKey] feature to the Id. The Code should be as follows:

public class Post{    [DataWebKey]    public int Id { get; set; }    public string Title { get; set; }    public string Author { get; set; }}

Add another Blog class, which has a property Posts with the return type IQueryable <Post>:

Public class Blog {public Blog () {_ post. add (new Post {Id = 1, Title = "one-step learning Silverlight 2 series (13): WebRequest for data and communication", Author = "TerryLee"}); _ post. add (new Post {Id = 2, Title = "one-step learning Silverlight 2 series (12): WebClient for data and communication", Author = "TerryLee"}); _ post. add (new Post {Id = 3, Title = "one-step learning Silverlight 2 series (11): Data Binding", Author = "TerryLee"}); _ post. add (new Post {Id = 4, Title = "one-step learning Silverlight 2 series (10): using user controls", Author = "TerryLee"}); _ post. add (new Post {Id = 5, Title = "One step Silverlight 2 series (9): use the control template", Author = "TerryLee"}); _ post. add (new Post {Id = 6, Title = "one-step learning Silverlight 2 series (8): Using Style encapsulation controls", Author = "TerryLee "});} list <Post> _ post = new List <Post> (); public IQueryable <Post> Posts {get {return _ post. asQueryable <Post> ();}}}

Add an ADO. NET Data Service named BlogDataService. svc:

Implement services to inherit from generic WebDataService and set access permissions.

public class BlogDataService : WebDataService<Blog>{    public static void InitializeService(IWebDataServiceConfiguration config)    {        config.SetResourceContainerAccessRule("*", ResourceContainerRights.AllRead);    }}

Now our server is complete. Now we can access BlogDataService. svc in the browser. We should see the following interface:

You cannot see all Posts. You can enter http: // localhost: 8081/BlogDataService in the address bar. svc/Posts, the browser will open for Feed by default, you can view the source code, you will see all the content, the XML content is as follows (only list fragments ):

<? Xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <Feed xml: base = "http: // localhost: 8081/BlogDataService. svc/"...> <id> http: // localhost: 8081/BlogDataService. svc/Posts </id> <updated/> <title> Posts </title> <link rel = "self" href = "Posts" title = "Posts"/> <entry adsm: type = "TerryLee. silverlightWithDataServiceDemoWeb. post "& gt; <id> http: // localhost: 8081/BlogDataService. svc/Posts (1) </id> <updated/> <title/> <author> <name/> </author> <link rel = "edit" href = "Posts (1) "title =" Post "/> <content type =" application/xml "> <ads: Id adsm: type =" Int32 "> 1 </ads: Id> <ads: title> Silverlight 2 series (13): WebRequest for data and communication </ads: Title> <ads: Author> TerryLee </ads: author> </content> </entry>

To view the content of an article, enter http: // localhost: 8081/BlogDataService. svc/Posts (2), as shown in.

Of course, you can also perform other queries, such as filter and orderby, such as http: // localhost: 8081/BlogDataService. svc/Posts? $ Filter = Id eq 1 & $ orderby = Id, which is not described here. Now our data server is complete. The client is implemented below, and The XAML will not be posted. You can refer to the previous articles and use WebClient to obtain data. The returned result is an XML file:

private void UserControl_Loaded(object sender, RoutedEventArgs e){    Uri uri = new Uri("http://localhost:8081/BlogDataService.svc/Posts");    WebClient client = new WebClient();    client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);    client.OpenReadAsync(uri);}void client_OpenReadCompleted(object sender,OpenReadCompletedEventArgs e){    if (e.Error == null)    {            }}

We can use LINQ to XML to read data, and create a Post class in the Silverlight project to read data in the same way as the Post class:

XmlReader reader = XmlReader.Create(e.Result);XDocument postdoc = XDocument.Load(reader);XNamespace xmlns = "http://www.w3.org/2005/Atom";XNamespace ads = "http://schemas.microsoft.com/ado/2007/08/dataweb";var posts = from x in postdoc.Descendants(xmlns + "entry")            select new Post            {                Id = int.Parse(x.Descendants(ads + "Id").First().Value),                Title = x.Descendants(ads + "Title").First().Value,                Author = x.Descendants(ads + "Author").First().Value            };Posts.ItemsSource = posts;

The completed Code is as follows:

private void UserControl_Loaded(object sender, RoutedEventArgs e){    Uri uri = new Uri("http://localhost:8081/BlogDataService.svc/Posts");    WebClient client = new WebClient();    client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);    client.OpenReadAsync(uri);}void client_OpenReadCompleted(object sender,OpenReadCompletedEventArgs e){    if (e.Error == null)    {        XmlReader reader = XmlReader.Create(e.Result);        XDocument postdoc = XDocument.Load(reader);        XNamespace xmlns = "http://www.w3.org/2005/Atom";        XNamespace ads = "http://schemas.microsoft.com/ado/2007/08/dataweb";        var posts = from x in postdoc.Descendants(xmlns + "entry")                    select new Post                    {                        Id = int.Parse(x.Descendants(ads + "Id").First().Value),                        Title = x.Descendants(ads + "Title").First().Value,                        Author = x.Descendants(ads + "Author").First().Value                    };        Posts.ItemsSource = posts;    }}

The complete example is here, and the running result is the same as the previous one.

Conclusion

This article briefly introduces how to call ADO in Silverlight 2. NET Data Services. NET Data Services does not know much about it. If there are any errors, please correct them. You can download the sample code from here.

Next article: Step by Step Silverlight 2 series (18): RSS reader for integrated instances

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.