Search
一步一步学Silverlight 2系列(17):数据与通信之ADO.NET Data Services
概述
Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic, Visual C#, IronRuby, Ironpython,对JSON、Web Service、WCF以及Sockets的支持等一系列新的特性。《一步一步学Silverlight 2系列》文章将从Silverlight 2基础知识、数据与通信、自定义控件、动画、图形图像等几个方面带您快速进入Silverlight 2开发。
本文将简单介绍在Silverlight 2中如何调用ADO.NET Data Services。
准备知识
由于ADO.NET Data Services是在ASP.NET 3.5 Extensions中,所以在开始本文示例之前,首先要安装一下ASP.NET 3.5 Extensions最新版本,你可以从这里下载。安装完成后,在添加新项对话框中应该能够看到ADO.NET Data Service项:
ADO.NET Data Service允许应用程序把数据以服务的形式公开,这样我们就可以通过浏览器来直接访问数据,它支持开放的业界标准,如AtomPub和JSON。它支持标准的HTTP动作如POST、GET、PUT、DELETE,用来完成数据的创建、更新、删除和读取。ADO.NET Data Service的知识这里不再多说,大家可以去查看相关的资料。
简单示例
如果大家看了前面三篇文章的话,可能对于下面的这个界面已经很烦了,不过在本文我会仍然采用这个示例进行演示:)
建立完Silverlight 2项目之后,我们在Web项目中添加一个Post类:
public class Post { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } }
我们用Id作为Post的主键,这里需要添加对于Microsoft.Data.Web.dll程序集的引用,位于<盘符>\Program Files\Reference Assemblies\Microsoft\Framework\ASP.NET 3.5 Extensions下面,引入命名空间using Microsoft.Data.Web,并且为Id加上[DataWebKey]特性,最终完成后代码应该如下:
public class Post { [DataWebKey] public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } }
再添加一个Blog类,它有一个返回类型为IQueryable<Post>的属性Posts:
public class Blog { public Blog() { _post.Add(new Post { Id = 1, Title = "一步一步学Silverlight 2系列(13):数据与通信之WebRequest", Author = "TerryLee" }); _post.Add(new Post { Id = 2, Title = "一步一步学Silverlight 2系列(12):数据与通信之WebClient", Author = "TerryLee" }); _post.Add(new Post { Id = 3, Title = "一步一步学Silverlight 2系列(11):数据绑定", Author = "TerryLee" }); _post.Add(new Post { Id = 4, Title = "一步一步学Silverlight 2系列(10):使用用户控件", Author = "TerryLee" }); _post.Add(new Post { Id = 5, Title = "一步一步学Silverlight 2系列(9):使用控件模板", Author = "TerryLee" }); _post.Add(new Post { Id = 6, Title = "一步一步学Silverlight 2系列(8):使用样式封装控件观感", Author = "TerryLee" }); } List<Post> _post = new List<Post>(); public IQueryable<Post> Posts { get { return _post.AsQueryable<Post>(); } } }
添加一个ADO.NET Data Service,取名BlogDataService.svc:
实现服务,让它继承于泛型的WebDataService,并且设置访问权限。
public class BlogDataService : WebDataService<Blog> { public static void InitializeService(IWebDataServiceConfiguration config) { config.SetResourceContainerAccessRule("*", ResourceContainerRights.AllRead); } }
现在我们的服务端就完成了,现在我们可以在浏览器中访问BlogDataService.svc,应该可以看到如下界面:
现在还看不到所有的Posts,我们可以在地址栏中输入http://localhost:8081/BlogDataService.svc/Posts,浏览器会默认为Feed打开,可以查看源代码,将会看到所有内容,XML内容如下(只列出片段):
<?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"> <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系列(13):数据与通信之WebRequest</ads:Title> <ads:Author>TerryLee</ads:Author> </content> </entry>
如果要查看某一条文章的内容,可以输入http://localhost:8081/BlogDataService.svc/Posts(2)进行查看,如下图所示。
当然还可以进行其他的查询,使用filter和orderby等,如http://localhost:8081/BlogDataService.svc/Posts?$filter=Id eq 1&$orderby=Id,这里不在介绍。至此我们的数据服务端就算完成了。下面再实现客户端,XAML不再贴出来,大家可以参考前面的几篇文章,使用WebClient获取数据,返回的结果是一个XML文件:
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) { } }
我们可以使用LINQ to XML进行数据的读取,在Silverlight项目中建立一个Post类,跟上面的Post类一样,然后使用LINQ to XML读取:
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;
完成的代码如下所示:
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; } }
完整的示例就到这里了,运行后的结果与前面的一样。
结束语
本文简单介绍了在Silverlight 2调用ADO.NET Data Services,由于对ADO.NET Data Services了解不多,有错误的地方还请大家斧正,你可以从这里下载示例代码。


评论
ED hardy bikini
Ed Hardy Hats
ED hardy men jeans
ED hardy women jeans
ED mens hooded sweatshirts
ED womens hooded sweatshirts
Men's Ed Hardy T-Shirts
Women's Ed Hardy T-Shirts
ed hardy
ed hardy shirts
ed hardy sale
cheap ed hardy
ed hardy outlet
Beats By Dr. Dre Earphones
Monster Beats by Dre Studio
Monster Beats In Ear
Monster Beats Solo Headphones
Monster Butterfly
Monster Diddy Beats
Monster Heartbeats By Lady Gaga
Monster Miles Davis Tribute
monster beats pro
monster beats
dr dre beats
beats by dre
dre beats
dre headphone
Lady Gaga Heartbeats
Monster Beats Butterfly
Monster Beats by Dre Studio
Monster Beats Solo
Monster Beats Tour
Monster Diddy Beats
Monster Miles Davis Tribute
Monster beats dre
beats by monster
cheap beats headphones
Mens True Religion
Mens Bootcut
Mens Corduroy
Mens Flare
Mens Skinny
Mens Straight Leg
Mens T-shirts
Womens True Religion
Womens Bootcut
Womens Cargo
Womens Corduroy
Womens Crops
Womens Flare
Womens Legging
Womens Petite
Womens Shorts
Womens Skinny
Womens Straight Leg
cheap true religion
true religion jeans
cheap true religion
true religion sale
true religion outlet
Canada Goose Coats
Mens Coats
Womens Coats
Canada Goose Glove
Canada Goose Hats
Canada Goose Jackets
Canada Goose New Style
Canada Goose Parka
Chilliwack Parka
Expedition Parka
Mens Chateau Parka
Snow Mantra Parka
Womens Expedition Parka
Womens Montebello Parka
Womens Sollaris Parka
Womens Trillium Parka
Yorkville Parka
Canada Goose Vest
Mens Vest
Women Icicle Vest
Womens Vest
canada goose online
canada goose jacket
canada goose jackets
anada goose jakke
canada goose sale
moncler men
2011 moncler coat
moncler men coat
coats for men cheapMoncler Men's Vests
2011 moncler jackets
2011 Moncler Men
men cheap coatsaffordable winter coats menribera moncler
men winter coats 2011
black moncler nibble boot
2011 New Style Moncler Men Jackets Black
silver winter jacket
new moncler scarf hat black set
moncler scarfs in whole black
moncler scarf and hat set in grey
moncler scarf
moncler mens cheep
moncler men red black vests
moncler k2 women vests
moncler jacket outlet 2011
Moncler
Moncler Outlet
Moncler Men Jackets
The hottest new traditional and seasonal
coach outlet store online
. Keep up to date with the latest trends. Look at this zip top closure with colorful C logo printed fabric bag.You may find the most affordable Bags here.This brown handbag called Flagship Signature Brown Handbag has been the best seller in the
coach factory outlet
for almost three weeks.Everyone believes the fact that
coach outlet store online
can be well-known simply because of its high quality and the lovely pattern.My friend is dying to get a coach purse at
coach outlet store
because all of her friends have them at work. They earn great reputation from many people.The latest fashion collection contains those bags suitable to be worn in both casual and formal environment. We provide the best quality
louis vuitton uk
with the most reasonable price we can offer as you see in our online store.in fact,
louis vuitton
is one of the most famous fashion design master.he opened the fist suitcase shop called after his name.louis vuitton outlet
,welcome to buy urban louis vuitton on our online shop.discount price is our special offer, durability and high quality is our promise.They're not chosen, so one of these ideal for you.For more flexibleness a lot more like these, there are lots of discount 'shoulder' variations outlet
louis vuitton bags
.Show someone how much you care with this sophisticated and sparkling
christian louboutin
collection. Cut with exquisite detail, this can be a beautiful yet practical gift.All of the
armani watches
Denim handbags at the High quality, practical, timeless yet resolutely modern design with our professional and excellent service.You can choose the discount Louis Vuitton bags on our website. Cheap
emporio armani watches
are specifically designed to make a statement of fashion and elegance..With the safe door to door shipping, the
gucci outlet
will send the products to your hands, which are of top quality and at competitive factory prices.One of my friend wants to buy a gift for her mother on the Mother's Day. She asks me, I suggest her to buy
hermes bags
, which has good quality and unique design.I can't wait sharing the
hermes birkin
with you.It's an online crystal shopping paradise supplying delicate Swarovski jewelry.winding. The drawing near this commotion is that a derisory Herve leger replica rotor on the transfer of the watch's movement spins around herve leger dresses winding. The drawing near this commotion is that a derisory new omega watches for sale rotor on the transfer of the watch's movement spins around new omega watches for sale winding. The drawing near this commotion is that a derisory brian atwood fashion rotor on the transfer of the watch's movement spins around brian atwood winding. The drawing near this commotion is that a derisory christian louboutin shoes uk rotor on the transfer of the watch's movement spins around louboutin shoes uk
panies that swallow stuck to their guns when absolute comes designer shoes to the bent of the merchandise that they were founded designer handbags panies that swallow stuck to their guns when absolute comes designer louis vuitton handbags to the bent of the merchandise that they were founded louis vuitton sale panies that swallow stuck to their guns when absolute comes christian louboutin to the bent of the merchandise that they were founded christian louboutin panies that swallow stuck to their guns when absolute comes louboutin uk online to the bent of the merchandise that they were founded louboutin uk