WCF Data Service QuickStart

Source: Internet
Author: User
Tags management studio sql server management sql server management studio visual studio 2010

Open Data Protocol (ODATA) is a Web protocol that queries and updates data. OData is created based on international standards such as HTTP and AtomPub, which provides a Cross-platform data communication scheme. OData has applied web technologies such as HTTP, Atom Publishing Protocol (ATOMPUB), and JSON to provide access to information about different applications, services, and storage. SharePoint, SQL Server 2008 R2, PowerPivot, Windows Azure Table Storage, and third party products like IBM ' s WebSphere eXtreme scale all use ODA Ta.

First, WCF Data Services is a WCF service, so you can use all of the existing WCF knowledge. Second, WCF Data Services has implemented the OData topology, so you can focus on the presentation of your data format in your program, rather than atompub/json the data formats that are actually passed on the network. Again, WCF Data Services is committed to data transfer, not to the datastore. Your data can be stored in any location: Local database, Cloud database, external Web Services,xml file, and so on. No matter how the data comes, you can publish/use them in the same way.

Using the WCF Data Service in Visual Studio 2010, using the RESTful service published by OData, the following example shows the WCF data Service in 2010.

1, create a database, use SQL Server Management Studio and run this script.

A database was created, containing two tables categories and products, and two table heads were inserted 2 records.

2, create a Web application, and then create a entity Data Model, as shown in the following figure

3, create a data service to expose our model:

Using System;
Using System.Collections.Generic;
Using System.Data.Services;
Using System.Data.Services.Common;
Using System.Linq;
Using System.ServiceModel.Web;
Using System.Web;

Namespace MyWebsite
{
public class Productservice:dataservice<gettingstartedwithupdateentities>
{
This are called only once to initialize Service-wide policies.
public static void InitializeService (Dataserviceconfiguration config)
{
Todo:set rules to indicate which entity sets and service operations are, visible, etc.
Examples:
Config. Setentitysetaccessrule ("*", entitysetrights.allread);
Config. Setserviceoperationaccessrule ("*", serviceoperationrights.all);
Config. Dataservicebehavior.maxprotocolversion = Dataserviceprotocolversion.v2;
}
}
}

4, verify the Productservice service, view the productservice.svc in the browser, as shown in the following figure:

The image above is the AtomPub protocol, and first, you initiate a validated GET request (authenticated get) to the server's Atom link for a description of the currently available service. The server returns a (description) XML file for the Atom service, which lists some column workspace, each containing the corresponding collection collection. A workspace may be a blog, wiki namespace, or a set of content that can be accessed through your username/password.

Each workspace can contain five types of collections: entries (entries), categories (categories), templates (template), users (users), and integrated resources (generic).

Since a workspace is a product, the product generally contains a series of entries, products, etc. such a collection. All of these collections are processed and responded to in the same way (get,postd,elete,put) as the HTTP predicate is referred to. All of these (collections) support paging, so the server can return collections as an easily manageable block of data. It also supports querying by Date (collection), so you can filter collections by starting and ending date filters.

To obtain a collection, you can initiate a GET request to the URL (the address listed in the Service document collection ' href '). The service document specifies a URI for each collection. If you send a GET request to a URI, you will receive an XML file containing the Atom collection, which lists the first X members of the collection. If there are more than X members in the collection, the file will also contain a URI that points to the next group of members, which you can use to get the next batch of members. You can also specify a date range in the head of HTTP by range to restrict the returned collection to only those entries between the start and end dates.

We already have a service productservice.svc that exposes the V2 version of OData protocol, and below I create a WPF application to consume this service.

5, create a WPF application and add a PRODUCTSERVICE.SVC service reference.

You can use a plug-in Open data Protocol Visualizer to view the OData data data returned by the service, and the acquisition and installation of this tool can refer to the VS2010 extension. Can be viewed through the "view in Diagram" of the service reference.

The following figure is Productservice.svc's OData Model Brower:

6. Add a ViewModel, encapsulate DataServiceContext, act as a mediator between the WPF form and the data service interaction.

public class ViewModel
{
Private Gettingstartedwithupdateentities _ctx;
Private category[] _categories;
Private dataservicecollection<product> _products;

Public ViewModel ()
{
_ctx = new Gettingstartedwithupdateentities (
New Uri ("Http://localhost:1812/ProductService.svc/%22");
Load ();
}


Public dataservicecollection<product> Products
{
Get
{
return _products;
}
}


Public category[] Categories
{
Get
{
return _categories;
}
}


public void SaveChanges ()
{
_ctx. SaveChanges ();
Load ();
}


public void Load ()
{
_categories = _ctx. Categories.toarray ();
_products = new dataservicecollection<product> (_CTX);
_products. Load (from P in _ctx.) Products.expand ("Category")
Select p);
}
}

7. Make a WPF form

<window x:class= "Myclientapp.mainwindow"
Xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation%22
xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml%22
Title= "Products Catalog" height= "width=" "425" >
<Grid>
<stackpanel orientation= "Horizontal" >
<grid margin= "0,0,0,0" name= "Grid1" width= "140" >
<listbox itemssource= "{Binding path=products}"
Name= "Products"
issynchronizedwithcurrentitem= "True" >
<ListBox.ItemTemplate>
<DataTemplate>
<stackpanel orientation= "Horizontal" >
<textblock text= "{Binding path=name}" fontweight= "Bold"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
<stackpanel orientation= "Vertical" width= ">"
<stackpanel orientation= "Horizontal" >
<label name= "Lblname" width= ">"
<textblock width= ">Name:</TextBlock>"
</Label>
<textbox name= "Txtname"
text= "{Binding elementname=products, path=selecteditem.name, Mode=twoway}"
Width= "/>"
</StackPanel>
<stackpanel orientation= "Horizontal" >
<label name= "Lblcost" width= ">"
<textblock width= ">Cost:</TextBlock>"
</Label>
<textbox name= "Txtcost"
text= "{Binding elementname=products, path=selecteditem.cost, Mode=twoway}"
Width= "/>"
</StackPanel>
<stackpanel orientation= "Horizontal" >
<label name= "lblcategory" width= ">"
<TextBlock>Category:</TextBlock>
</Label>
<combobox name= "Cmbcategory"
Itemssource= "{Binding path=categories}"
Displaymemberpath= "Name"
Selectedvaluepath= "."
Selectedvalue= "{Binding elementname=products, path=selecteditem.category, Mode=twoway}"
Width= "140"/>
</StackPanel>
<button height= "23"
Horizontalalignment= "Right"
Name= "Btnsavechanges"
Verticalalignment= "Bottom"
Width= "136"
click= "Btnsavechanges_click" >save changes</button>
</StackPanel>
</StackPanel>
</Grid>
</Window> write the following codebehind code:

Namespace Myclientapp
{
<summary>
Interaction logic for MainWindow.xaml
</summary>
public partial class Mainwindow:window
{
ViewModel ViewModel = new ViewModel ();

Public MainWindow ()
{
InitializeComponent ();
This.cmbCategory.DataContext = ViewModel;
This.grid1.DataContext = ViewModel;
}

private void Btnsavechanges_click (object sender, RoutedEventArgs e)
{
ViewModel. SaveChanges ();
This.grid1.DataContext = ViewModel;
}

}
}

The results of running the program are as follows:

This article code downloads: Http://files.cnblogs.com/shanyou/MyWebsite.zip

Reference resources: Breaking down ' data Silos ' –the Open data Protocol (OData), Getting started with the "Data Services Update for. NET 3 .5 Sp1–part 1 Getting started with the Data Service Update for. NET 3.5 Sp1–part 2 Introducing the Microsoft Open Data Protocol Visualizer (CTP1)

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.