Date post: | 06-May-2015 |
Category: |
Technology |
Upload: | goodfriday |
View: | 1,751 times |
Download: | 5 times |
Working with Data and Web Servicesin Silverlight 2Eugene Osovetsky
Program Manager, Connected SystemsMicrosoft Corporation
Applications interact with the outside world
Product catalog
Search stringProductdatabaseProduct information
Mapping MashupCoordinates
MapProviderMap images
Applications interact with the outside world
Coordinates
LocationdatabasePoints of Interest
Many Types of Outside Data
In-Browser Application
PublicInternetmashup APIs
ExistingIntranetservices
New servicesyou build
RSS/AtomFeeds
ImagesSoundsVideos
A Bit of History: Silverlight 1.0
PublicInternetmashup APIs
ExistingIntranetservices
New servicesyou build
RSS/AtomFeeds
ImagesSoundsVideos
JavaScript
HTML
?AJAX (XmlHttpRequest)
1.0
<XAML/>
2
Managed Code (C#/VB)
The Story Today: Silverlight 2
PublicInternetmashup APIs
ExistingIntranetservices
New servicesyou build
RSS/AtomFeeds
ImagesSoundsVideos
HTML
Question 1:
What does the client code look like?
Managed Code (C#/VB)
2
New servicesyou build
Question 2:
What is the recommended way tocreate services for Silverlight?
DEMO
Product Catalog – Using a Custom Service from Silverlight
ServiceProductdatabase
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
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”…>
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!
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)
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
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
Data Binding to Services
• All generated types/collections support data binding
• Future Possibility: Advanced data binding to services (XAML-only)
E.g. <GetProductsDataSource />
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
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)
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
What we covered so far…
2
PublicInternetmashup APIs
ExistingIntranetservices
New servicesyou build
RSS/AtomFeeds
ImagesSoundsVideos
But what about the client code for other service types?
Approach #1:"Add Service Reference"
Metadata-driven, with Intellisense
Services that Describe Themselves
SOAPservices in the enterprise
Services for your Silverlightproject
SQL ServerData Services*(Astoria)
SOAP serviceson the Internet
Computer-ReadableMetadata
(e.g. WSDL)
AutomaticProxy
Generation
WCF
Demo:Accessing the Live Search APIfrom Silverlight in an automatic way
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…
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
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?
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)
Cross-Domain Policy Files
Silverlight looks for two policy files:Silverlight policy: clientaccesspolicy.xmlAdobe Flash policy: crossdomain.xmlAlready used by etc…
All public services that work with Flash – will also work with Silverlight
Quick Demo:
Existing Services withCross-Domain Policy Files
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
Approach #2:Write the Code Manually
“A service call is just an HTTP request”
Human-Readable Documentation Only
Services that Don’t Describe Themselves
RESTServices
“Mashup APIs” “Web APIs”
JSONServices
“POX”(Plain Old XML)services
Human-ReadableDocumentation
SomeManual
Work Required
1. Build a URL2. Make a request3. Work with request/response data (XML or JSON)
Demo:Accessing Flickr from Silverlight
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…
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?
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?
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
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?
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
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
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?
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
Supported HTTP Features
Silverlight exposes all HTTP features that the browsers make available
Supported features are equivalent to Flash
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
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
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?
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
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
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
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?
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}}
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}]}
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}}
Approach #3:Use Built-In Classes
… for RSS/Atom feeds
Consuming Feeds
Atom 1.0Feeds
RSS 2.0Feeds
AtomPublishing(Future?)
Conform to a Standard
Built-in classes
to work withsuch services
SyndicationFeed feed = SyndicationFeed.Load(…)
foreach (SyndicationItem item in feed){ //Do something with item}
Demo:Accessing Live Expo from Silverlightusing RSS support
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
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>”
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
© 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.
BACKUP
Security Considerations
• Denial of Service• No protection (for now?)• Browser may hang if talking to malicious service
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”
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
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
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
• 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
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
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
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
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
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)
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
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
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
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
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