+ All Categories
Home > Technology > Working with Data and Web Services in Microsoft Silverlight 2

Working with Data and Web Services in Microsoft Silverlight 2

Date post: 06-May-2015
Category:
Upload: goodfriday
View: 1,751 times
Download: 5 times
Share this document with a friend
Description:
Learn how easy it is to utilize POX, REST, RSS, ATOM, JSON, and SOAP in your Microsoft Silverlight mashup applications. Also learn how to easily access and display data with Silverlight using LINQ and databinding.
79
Working with Data and Web Services in Silverlight 2 Eugene Osovetsky Program Manager, Connected Systems Microsoft Corporation [email protected]
Transcript
Page 1: Working with Data and Web Services in Microsoft Silverlight 2

Working with Data and Web Servicesin Silverlight 2Eugene Osovetsky

Program Manager, Connected SystemsMicrosoft Corporation

[email protected]

Page 2: Working with Data and Web Services in Microsoft Silverlight 2

Applications interact with the outside world

Product catalog

Search stringProductdatabaseProduct information

Page 3: Working with Data and Web Services in Microsoft Silverlight 2

Mapping MashupCoordinates

MapProviderMap images

Applications interact with the outside world

Coordinates

LocationdatabasePoints of Interest

Page 7: Working with Data and Web Services in Microsoft Silverlight 2

Question 1:

What does the client code look like?

Managed Code (C#/VB)

2

Page 10: Working with Data and Web Services in Microsoft Silverlight 2

Required StepsWCFService

1. Create the Service2. Define what it does

3. “Add Service Reference”4. Use the Service!

We’ll also cover:- Migrating service usage from SL 1.1 Alpha- Securing services

Page 11: Working with Data and Web Services in Microsoft Silverlight 2

Creating a Service for Silverlight“Add New Item” (in Web Site / Web App) “Silverlight-Enabled WCF Service”

Temporary for Beta1:“Add New Item” “WCF Service”Change wsHttpBinding basicHttpBinding in config

basicHttpBinding <endpoint contract=“IShoppingService” binding=“wsHttpBinding”…>

Page 12: Working with Data and Web Services in Microsoft Silverlight 2

Defining the Contract[ServiceContract] for the service class (interface in Beta1)[OperationContract] for methods (in the interface in Beta1)[DataContract]/[DataMember] for data types

[ServiceContract]public class ShoppingService {

[OperationContract]Product[] GetProducts(string searchString){ /*... Implementation ... */ }

}

[DataContract] public class Product {

[DataMember]public string description;[DataMember]public string pictureUrl;

}

Nothing Silverlight-specific

Regular WCF code!

Page 13: Working with Data and Web Services in Microsoft Silverlight 2

Adding a ReferenceIn the Silverlight project: “Add Service Reference”

“Discover” button will find services in solutionCan also give external URL (more on this later)

After Beta1: command-line equivalent (slsvcutil.exe)

Page 14: Working with Data and Web Services in Microsoft Silverlight 2

Creating the Proxy

• var proxy = new ShoppingServiceClient();• Default address chosen if no parameters given

• Can pass in address manually

• But what if the service moves?• Configuration support after Beta1• No need to recompile Silverlight client code if service moves• Can reuse one Silverlight app for many services

Page 15: Working with Data and Web Services in Microsoft Silverlight 2

Making the Call

• Only asynchronous calls supported• Set up GetProductsCompleted event

• “Tab,Tab” in Visual Studio• Call GetProductsAsync

var proxy = new ShoppingServiceClient();proxy.GetProductsCompleted +=

new EventHandler<GetProductsCompletedEventArgs>(proxy_GetProductsCompleted);

proxy.GetProductsAsync(“book”);

void proxy_GetProductsCompleted(object sender, GetProductsCompletedEventArgs e)

{// Process response…

}

Tab Tab

Page 16: Working with Data and Web Services in Microsoft Silverlight 2

Data Binding to Services

• All generated types/collections support data binding

• Future Possibility: Advanced data binding to services (XAML-only)

E.g. <GetProductsDataSource />

Page 17: Working with Data and Web Services in Microsoft Silverlight 2

Migrating from SL1.1 Alpha Services

• Breaking change on the Client-side• Remove “Web References”• Do “Add Service Reference”• FYI: Data format is now SOAP, not JSON

• Server-side code does not have to change in most cases• Details in documentation

Page 18: Working with Data and Web Services in Microsoft Silverlight 2

Securing Silverlight ServicesSilverlight will use auth. information in the browser

HTML

E.g.: ASP.NET login

User:Password:

YourDomain.comCredentials

Auth info (e.g. cookie)

Service calls + Auth info

Silverlight code does not normallydeal with credentials (user, password)

Page 19: Working with Data and Web Services in Microsoft Silverlight 2

Securing Silverlight ServicesSilverlight will use auth. information in the browser

This is exactly what you want!Login once for web page + Silverlight

To get user identity in WCF Services: Turn ASP.NET Compat Mode on (template will do this for you)HttpContext.Current.User – current user

Page 21: Working with Data and Web Services in Microsoft Silverlight 2

Approach #1:"Add Service Reference"

Metadata-driven, with Intellisense

Page 23: Working with Data and Web Services in Microsoft Silverlight 2

Demo:Accessing the Live Search APIfrom Silverlight in an automatic way

Page 24: Working with Data and Web Services in Microsoft Silverlight 2

Add Service ReferenceWorks with:

Any “simple” SOAP service (e.g. Live Search)

SOAP 1.1 (Basic Profile – compatible)Server-side may be JAVA, WCF, ASMX, etc.A few restrictions (e.g. SOAP Faults not supported)

Future Possibility: SQL Server Data Services (Astoria)

Can’t talk to just any service… Silverlight-Wide Cross-Domain Restrictions…

Page 25: Working with Data and Web Services in Microsoft Silverlight 2

Why is Cross-Domain an Issue?

MyBank.com Login

User:Password:

MyBank.comCredentials

Auth info (e.g. cookie)

Malicious call + Auth info

EvilApps.comMalicious application

Could steal orchange dataif protection wasn’t in place

Page 26: Working with Data and Web Services in Microsoft Silverlight 2

Cross-Domain RestrictionsSilverlight does not allow applications to cross domain boundaries by default

MySite.com/silverlightApplication.xapcannot call

SomeOtherSite.com/someService.svc

SecurityException if you try

Silverlight allows the calls if target site opts in

How do services opt in?When should services opt-in?

Page 27: Working with Data and Web Services in Microsoft Silverlight 2

Cross-Domain Opt-in: Policy File

On first call to MyBank.com:http://MyBank.com/clientaccesspolicy.xmlDoes not exist:SecurityException will be thrown

EvilApps.com MyBank.com

SL app from EvilApps.com

InnocentMashups.com

Weather.com

SL app from InnocentMashups.com

On first call to Weather.com:http://weather.com/clientaccesspolicy.xmlExists:Silverlight will let the call go through (if policy allows)

Page 29: Working with Data and Web Services in Microsoft Silverlight 2

Quick Demo:

Existing Services withCross-Domain Policy Files

Page 30: Working with Data and Web Services in Microsoft Silverlight 2

Should a Service Opt In to Cross-Domain?“Private” services (for your own app)

DO use browser-based authenticationCookies, HTTP Auth, etc.

DO NOT enable public access via cross-domain policy file

“Public” services (for 3rd-party apps)DO NOT use browser-based authenticationDO publish cross-domain policy files

DO use “cross-domain-safe” authenticationE.g. URL signatures

DO separate public services in their own domain

E.g. api.flickr.com vs. www.flickr.com

Page 31: Working with Data and Web Services in Microsoft Silverlight 2

Approach #2:Write the Code Manually

“A service call is just an HTTP request”

Page 32: Working with Data and Web Services in Microsoft Silverlight 2

Human-Readable Documentation Only

Page 34: Working with Data and Web Services in Microsoft Silverlight 2

Demo:Accessing Flickr from Silverlight

Page 35: Working with Data and Web Services in Microsoft Silverlight 2

Manually Issuing Requests

Code was exactly as in the regular .NET Framework!

Good news for existing .NET developers

Some Silverlight-specific things to be aware of…

Page 36: Working with Data and Web Services in Microsoft Silverlight 2

Manually Issuing Requests

Build a URLWhat are the allowed protocols?Where can I connect to?

Make a RequestHow do I make a request?What are the restrictions on requests?

Working with Request/Response DataHow do I work with XML?How do I work with JSON?

Page 37: Working with Data and Web Services in Microsoft Silverlight 2

Manually Issuing Requests

Build a URLWhat are the allowed protocols?Where can I connect to?

Make a RequestHow do I make a request?What are the restrictions on requests?

Working with Request/Response DataHow do I work with XML?How do I work with JSON?

Page 38: Working with Data and Web Services in Microsoft Silverlight 2

Allowed URLsHTTP and HTTPS

Some restrictions on HTTPS, cross-schemeA few of these will go away after Beta1

Subject to cross-domain rulesMust have policy file if not local URL

No ftp:// or file:// URLs

Sockets support for non-HTTP Services

Originating server only (in Beta1)Port number restrictionsNot in scope for this talk

Page 39: Working with Data and Web Services in Microsoft Silverlight 2

Manually Issuing Requests

Build a URLWhat are the allowed protocols?Where can I connect to?

Make a RequestHow do I make a request?What are the restrictions on requests?

Working with Request/Response DataHow do I work with XML?How do I work with JSON?

Page 40: Working with Data and Web Services in Microsoft Silverlight 2

Making HTTP RequestsWebClient

Simple to useLimited functionality

HttpWebRequestAccess to all features

Future possibility:Usability Improvements to HTTP client

Serializer integration, URI templates, etc.Available as a samplehttp://code.msdn.microsoft.com/SilverlightWS

Page 41: Working with Data and Web Services in Microsoft Silverlight 2

Asynchronous RequestsWebClient w = new WebClient();

w.DownloadStringCompleted +=new DownloadStringCompletedEventHandler

(w_DownloadStringCompleted);

w.DownloadString(myUri);

static void w_DownloadStringCompleted(object sender,

DownloadStringCompletedEventArgs e){

// Process the response ...}

Only Async supported – otherwise browser would hangCalling from non-UI thread (sync/async) – not supported

Tab Tab

Page 42: Working with Data and Web Services in Microsoft Silverlight 2

Manually Issuing Requests

Build a URLWhat are the allowed protocols?Where can I connect to?

Make a RequestHow do I make a request?What are the restrictions on requests?

Working with Request/Response DataHow do I work with XML?How do I work with JSON?

Page 43: Working with Data and Web Services in Microsoft Silverlight 2

HttpWebRequest

High-level components and User Code

Browser Plugin APIs

Web Browser- Cookies- Authenticated sessions- Caching- Proxy server to use

Windows/MacNetworking Layer

HTTP Requests in Silverlight

Restrictions

Restrictions

Page 44: Working with Data and Web Services in Microsoft Silverlight 2

Supported HTTP Features

Silverlight exposes all HTTP features that the browsers make available

Supported features are equivalent to Flash

Page 45: Working with Data and Web Services in Microsoft Silverlight 2

HTTP Features: DetailsHTTP GET and POST

No PUT, DELETE, …

Setting headers on HTTP GET: only same domainResponse headers: can only read Content-Type

Response codes: only success/failNo 403/404/etc, no message bodyRedirects: Work (may be blocked in cross-domain)

Cannot override the browserCan’t control / turn off cachingCan’t control HTTP Authentication credentialsCan’t read/write cookiesCan’t control HTTPS Client-Side CertificatesCan’t read HTTPS Server-Side Certificates

Page 46: Working with Data and Web Services in Microsoft Silverlight 2

What do the Restrictions Really Mean?Cross-Domain and HTTP restrictions:Some services not accessible from rich browser apps (both Flash and Silverlight)

Change must come from:Browser APIs - IE, NPAPI (Safari & FireFox)Service Owners

e.g. Google allows X-Http-Verb-Override:DELETE inst. of HTTP DELETE

Can use a proxy:SL app

Page 47: Working with Data and Web Services in Microsoft Silverlight 2

Manually Issuing Requests

Build a URLWhat are the allowed protocols?Where can I connect to?

Make a RequestHow do I make a request?What are the restrictions on requests?

Working with Request/Response DataHow do I work with XML?How do I work with JSON?

Page 48: Working with Data and Web Services in Microsoft Silverlight 2

Working with XMLXmlReader/XmlWriterLinq to XML

static void w_DownloadStringCompleted(object senderDownloadStringCompletedEventArgs e)

{ XElement x = XElement.Parse(e.Result); foreach (photo in x.Elements("photo")) { //... } }

XmlSerializer

Page 49: Working with Data and Web Services in Microsoft Silverlight 2

The XmlSerializerPre-build a type using XML Attributespublic class Photo

{ [XmlElement] public string photoName;

[XmlElement] public string location;[XmlAttribute] public string size;

}

Serialize / DeserializeXmlSerializer xs = new XmlSerializer(typeof(Photo));Photo p = (Photo) xs.Deserialize(myHttpResponseStream);string name = p.photoName;

Requires manual work to build the type

Page 50: Working with Data and Web Services in Microsoft Silverlight 2

Future Possibility: "Paste as XmlSerializable"

public class Video { [XmlElement] public string author;

[XmlElement] public string id;[XmlElement] public string title;[XmlElement] public string url;

}

Functionality already available in XSD.EXE tool

Copy

Paste

Page 51: Working with Data and Web Services in Microsoft Silverlight 2

Manually Issuing Requests

Build a URLWhat are the allowed protocols?Where can I connect to?

Make a RequestHow do I make a request?What are the restrictions on requests?

Working with Request/Response DataHow do I work with XML?How do I work with JSON?

Page 52: Working with Data and Web Services in Microsoft Silverlight 2

The JSON Data Format“JavaScript Object Notation”

Easy and fast to parse in JavaScript in browsers

Often no real reason to use it for SL, except…

Reusing existing services built for AJAX pagesSmaller message size (but binary XML is a future possibility)

Example:{“Person”:{“name”:”john”,”age”:42}}

Page 53: Working with Data and Web Services in Microsoft Silverlight 2

Working with JSON“Linq to JSON” (currently a sample)http://code.msdn.microsoft.com/SilverlightWS

JsonObject j = JsonObject.Load(myString)int a = j[“Person”][“age”];{“Person”:{“name”:”john”,”age”:42}}

var cities = from JsonBaseType city in jObj[“cities"]select new CityDisplay {Name = city["name"],

Population = city["population"] };

{“cities”:[{“name”:”Vegas”,”population”:1000},{“name”:”Seattle”,”population”:2000}]}

Page 54: Working with Data and Web Services in Microsoft Silverlight 2

Working with JSONUsing the DataContractJsonSerializerpublic class Person {

public string name;public int age;

}

Pre-build type, then deserialize and use

{“Person”:{“name”:”john”,”age”:42}}

Page 55: Working with Data and Web Services in Microsoft Silverlight 2

Approach #3:Use Built-In Classes

… for RSS/Atom feeds

Page 57: Working with Data and Web Services in Microsoft Silverlight 2

Demo:Accessing Live Expo from Silverlightusing RSS support

Page 58: Working with Data and Web Services in Microsoft Silverlight 2

Syndication Support in SilverlightProtocols

RSS 2.0, Atom 1.0Future possibility: Atom Publishing Protocol

Essentially the same as in .NET 3.5SyndicationFeed, SyndicationItem, etc.Can read / write feeds“Feed Extensions” exposed as XML

Subject to same cross-domain restrictions, etc.Use HttpWebRequest/WebClient, then Syndication to parse

Page 59: Working with Data and Web Services in Microsoft Silverlight 2

Syndication Data Binding<Canvas x:Name="LayoutRoot" > <ItemsControl x:Name="feedContent" ItemsSource="{Binding}"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel

Margin="0, 0, 0, 20"> <TextBlock Text="{Binding Title.Text}" Foreground="Maroon" /> <TextBlock Text="{Binding PublishDate}” Width="170" FontSize="11" />

</StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Canvas>

XmlReader reader = XmlReader.Create(myStream);SyndicationFeed feed = SyndicationFeed.Load(reader);LayoutRoot.DataContext = feed.Items;

Future Possibility: XAML-only RSS consumption“<RssDataSource>”

Page 60: Working with Data and Web Services in Microsoft Silverlight 2

Summary: What We Covered

Creating Services for SilverlightCreating and consuming WCF servicesSecuring local servicesCreating public services (safe for cross-domain)

Accessing Services that Describe Themselves“Add Service Reference”

Accessing Services that Don’t Describe ThemselvesWebClient / HttpWebRequest, manual work

Accessing FeedsRSS/Atom

Page 61: Working with Data and Web Services in Microsoft Silverlight 2

© 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.

The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the

date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Page 62: Working with Data and Web Services in Microsoft Silverlight 2

BACKUP

Page 63: Working with Data and Web Services in Microsoft Silverlight 2

Security Considerations

• Denial of Service• No protection (for now?)• Browser may hang if talking to malicious service

Page 64: Working with Data and Web Services in Microsoft Silverlight 2

Timeline

SL 1.0

•Beta at MIX 07•Shipped in Sep. 07

SL1.1 Alpha

•Demonstratedat MIX 07

SL1.1

Alpha

Refresh

•Sep. 07

SL1.1

Dec CTP

SL 2

Beta1

No service consumption

“Full” service consumption story“Temporary”

story

(Consume ASP.NET AJAX services only)

Nothing you will see today is “set in stone”

Page 65: Working with Data and Web Services in Microsoft Silverlight 2

Core: Small initial download Only critical pieces

Extensions: Additional .dlls (possibly hosted at Microsoft) Same security restrictions as user code

Can be downloaded automatically – no need to ask the user Main XAML file lists required extensions

Aside: Core vs. Extensions

Page 66: Working with Data and Web Services in Microsoft Silverlight 2

SOAP in Silverlight: Architecture and Extensibility

WCF Channel Stack

Various ChannelsUser-defined

EncodersTextual XML

User-defined

Binary XML

Transport ChannelsHTTP(S) User-

definedDuplex HTTP

Generated Proxy (Simple)Proxy Runtime (Simple)

Generated Proxy (Complex)Proxy Runtime (Complex)

Custom / UserCode

Duplex

Streaming

Extensibility

In Core

Possible

In Extension

Page 67: Working with Data and Web Services in Microsoft Silverlight 2

Most services (SOAP, REST/POX, RSS/Atom feeds, …) accessable via HTTP

How it works:

HTTP Stack

HttpWebRequest

High-level componentsWeb services proxies, Downloader control, …

Browser Plugin APIsIE/Firefox/Safari

XmlHttpWebRequestJavaScript

User codeE.g. POX

Web Browser- Cookies, authentication info- Caching- Proxy server to use

Windows/Mac Networking Layer

Page 68: Working with Data and Web Services in Microsoft Silverlight 2

• AJAX: Uses “JSONP” data format– <script src = “…”> allows cross-domain

– HTML DOM: <script src=“http://weather.com/GetWeather?zip=98052”>

– Returns: function getResult { return {“temp”:59,”descr”:”cloudy”}}

– Used by EBay, Facebook, Yahoo, Del.Icio.Us, Flickr, …

– Requires special format, only works for AJAX

Cross-Domain Calls: Service Opt-In: AJAX

Page 69: Working with Data and Web Services in Microsoft Silverlight 2

Cross-Domain Restrictions

How do we know when cross-domain access is safe?

Rule of thumb: Can it be done without SL?

EvilApps.com http://financeData

SL app from EvilGames.com

InnocentMashups.com

Weather.com

SL app from InnocentMashups.com

Page 70: Working with Data and Web Services in Microsoft Silverlight 2

Cross-Domain Restrictions

• Only the target service knowsif it’s safe to call it in a cross-domain way

Origin URL Target URL

SL app from Origin URL

Client Location

Page 71: Working with Data and Web Services in Microsoft Silverlight 2

Cross-Domain Restrictions• Definition of cross-domain:

E.g. from http://foo.com/myApp.xap

• Considered cross-domain if:– Different domain: http://bar.com/service.svc– Different subdomain: http://xyz.foo.com/service.svc– Different scheme: https://foo.com/service.svc– Different port: http://foo.com:5050/service.svc

• Allowed: http://foo.com:80/bar/service.svc

Page 72: Working with Data and Web Services in Microsoft Silverlight 2

Cross-Domain Policy Files

• Checked at the root of the domain• E.g. request to http://foo.com/bar/service.svc– Check http://foo.com/clientaccesspolicy.xml– If not - check http://foo.com/crossdomain.xml– If not – request fails, SecurityException

Page 73: Working with Data and Web Services in Microsoft Silverlight 2

ClientAccessPolicy.xml<access-policy> <cross-domain-access> <policy> <allow-from>

<domain uri=“*"/> <!-- or just YourDomain.com -->

</allow-from> <grant-to> <resource path="/" include-subpaths="true"/> </grant-to> </policy> </cross-domain-access></access-policy>

• Can have multiple <policy> elements (ORed together)

Page 74: Working with Data and Web Services in Microsoft Silverlight 2

Unsafe for Cross-Domain

Origin URL Target URL

SL app from Origin URL

Relying on:

Anything in the browserCookiesAuthenticated Sessions

Zone (intranet) boundaryIP-address restrictions…

Client Location

Page 75: Working with Data and Web Services in Microsoft Silverlight 2

Safe for Cross-Domain• Relying on:

– The message contents, or– The request URL

http://api.myservice.com/ErasePicture?pictureName=Sunset123&album=nature&authToken=a4563c5ff0

• E.g. OAuth standard

Page 76: Working with Data and Web Services in Microsoft Silverlight 2

Restrictions• Cross-domain access– Silverlight-wide restrictions on accessing data

cross-domain– Add Service Reference is “smart” –

will try and warn you if this is an issue• SOAP Faults not supported– Remember the HTTP Error Code restriction?

• Restrictions likely to go away after the Beta:– No one-way operations– Some schema not supported– No SOAP headers from WSDL

Page 77: Working with Data and Web Services in Microsoft Silverlight 2

Creating the Proxy

• After Beta1: Address Change Support• No longer need to recompile application if service moves• Easy to write reusable components• Easy to move between dev box / staging / production

WeatherServiceClient proxy = new WeatherServiceClient();

Silverlight .XAP package

YourApplication.dll

ServiceReferences.clientConfig

(other files…)

<endpoint address=“http://new.address.live.com” … />(subset of WCF configuration)

The .XAP package is just a renamed .ZIP file

Page 78: Working with Data and Web Services in Microsoft Silverlight 2

Migrating from SL1.1 Alpha Services

• Breaking change on the Client-side• Remove “Web References”• Do “Add Service Reference”• FYI: Data format is now SOAP, not JSON

• Server-side code does not have to change• ASMX JSON services always do SOAP as well• WCF JSON services – can add SOAP with simple

config change• Some edge-case services that do JSON-specific

things may require server-side changes

Page 79: Working with Data and Web Services in Microsoft Silverlight 2

Recommended