Working with Data and Web Services in Microsoft Silverlight 2

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Favorites, Groups & Events

    Working with Data and Web Services in Microsoft Silverlight 2 - Presentation Transcript

    1. Product catalog Search string Product database Product information
    2. Mapping Mashup Coordinates Map Map images Provider Coordinates Location Points of Interest database
    3. Images Sounds Videos RSS/Atom Feeds New services you build In-Browser Application Existing Intranet services Public Internet mashup APIs
    4. Images <XAML/> Sounds Videos 1.0 RSS/Atom Feeds New services you build JavaScript ? AJAX (XmlHttpRequest) Existing Intranet services Public Internet mashup APIs HTML
    5. Images Sounds Videos RSS/Atom 2 Feeds New services you build Managed Code (C#/VB) Existing Intranet services Public Internet mashup APIs HTML
    6. 2 Managed Code (C#/VB)
    7. New services you build
    8. Product Service database
    9. WCF Service 1. Create the Service 2. 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
    10. “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”…>
    11. [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 ... */ } } Nothing Silverlight-specific [DataContract] public class Product { Regular WCF code! [DataMember] public string description; [DataMember] public string pictureUrl; }
    12. In the Silverlight project: “Add Service Reference” “Discover” button will find services in solution Can also give external URL (more on this later) After Beta1: command-line equivalent (slsvcutil.exe)
    13. 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 •
    14. Only asynchronous calls supported • Set up GetProductsCompleted event • “Tab,Tab” in Visual Studio • Call GetProductsAsync • var proxy = new ShoppingServiceClient(); Tab Tab proxy.GetProductsCompleted += new EventHandler<GetProductsCompletedEventArgs> (proxy_GetProductsCompleted); proxy.GetProductsAsync(“book”); void proxy_GetProductsCompleted(object sender, GetProductsCompletedEventArgs e) { // Process response… }
    15. All generated types/collections support data binding • Future Possibility: • Advanced data binding to services (XAML-only) E.g. <GetProductsDataSource />
    16. 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 •
    17. Silverlight will use auth. information in the browser E.g.: ASP.NET login Credentials User: YourDomain.com Password: Auth info (e.g. cookie) Service calls + Auth info Silverlight code does not normally HTML deal with credentials (user, password)
    18. Silverlight 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
    19. Images Sounds Videos RSS/Atom 2 Feeds New services you build Existing Intranet services Public Internet mashup APIs
    20. Metadata-driven, with Intellisense
    21. Services for your Silverlight project WCF SOAP services in the enterprise SOAP Automatic Computer-Readable services Proxy Metadata on the Internet Generation (e.g. WSDL) SQL Server Data Services* (Astoria)
    22. Works 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…
    23. MyBank.com Login Credentials User: MyBank.com Password: Auth info (e.g. cookie) Could steal or change data Malicious call + Auth info if protection wasn’t in place Malicious application EvilApps.com
    24. Silverlight does not allow applications to cross domain boundaries by default MySite.com/silverlightApplication.xap cannot 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?
    25. SL app from InnocentMashups.com SL app from EvilApps.com InnocentMashups.com Weather.com EvilApps.com MyBank.com On first call to MyBank.com: http://MyBank.com/clientaccesspolicy.xml Does not exist: SecurityException will be thrown On first call to Weather.com: http://weather.com/clientaccesspolicy.xml Exists: Silverlight will let the call go through (if policy allows)
    26. Silverlight looks for two policy files: Silverlight policy: clientaccesspolicy.xml Adobe Flash policy: crossdomain.xml Already used by etc… All public services that work with Flash – will also work with Silverlight
    27. “Private” services (for your own app) DO use browser-based authentication Cookies, HTTP Auth, etc. DO NOT enable public access via cross-domain policy file “Public” services (for 3rd-party apps) DO NOT use browser-based authentication DO publish cross-domain policy files DO use “cross-domain-safe” authentication E.g. URL signatures DO separate public services in their own domain E.g. api.flickr.com vs. www.flickr.com
    28. “A service call is just an HTTP request”
    29. “Mashup APIs” “Web APIs” REST Services “POX” Some Human-Readable (Plain Old XML) Manual Documentation services Work Required JSON Services 1. Build a URL 2. Make a request 3. Work with request/response data (XML or JSON)
    30. Code was exactly as in the regular .NET Framework! Good news for existing .NET developers Some Silverlight-specific things to be aware of…
    31. Build a URL What are the allowed protocols? Where can I connect to? Make a Request How do I make a request? What are the restrictions on requests? Working with Request/Response Data How do I work with XML? How do I work with JSON?
    32. Build a URL What are the allowed protocols? Where can I connect to? Make a Request How do I make a request? What are the restrictions on requests? Working with Request/Response Data How do I work with XML? How do I work with JSON?
    33. HTTP and HTTPS Some restrictions on HTTPS, cross-scheme A few of these will go away after Beta1 Subject to cross-domain rules Must 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 restrictions Not in scope for this talk
    34. Build a URL What are the allowed protocols? Where can I connect to? Make a Request How do I make a request? What are the restrictions on requests? Working with Request/Response Data How do I work with XML? How do I work with JSON?
    35. WebClient Simple to use Limited functionality HttpWebRequest Access to all features Future possibility: Usability Improvements to HTTP client Serializer integration, URI templates, etc. Available as a sample http://code.msdn.microsoft.com/SilverlightWS
    36. WebClient w = new WebClient(); Tab Tab 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 hang Calling from non-UI thread (sync/async) – not supported
    37. Build a URL What are the allowed protocols? Where can I connect to? Make a Request How do I make a request? What are the restrictions on requests? Working with Request/Response Data How do I work with XML? How do I work with JSON?
    38. High-level components and User Code HttpWebRequest Browser Plugin APIs Restrictions Web Browser - Cookies - Authenticated sessions Restrictions - Caching - Proxy server to use Windows/Mac Networking Layer
    39. Silverlight exposes all HTTP features that the browsers make available Supported features are equivalent to Flash
    40. HTTP GET and POST No PUT, DELETE, … Setting headers on HTTP GET: only same domain Response headers: can only read Content-Type Response codes: only success/fail No 403/404/etc, no message body Redirects: Work (may be blocked in cross-domain) Cannot override the browser Can’t control / turn off caching Can’t control HTTP Authentication credentials Can’t read/write cookies Can’t control HTTPS Client-Side Certificates Can’t read HTTPS Server-Side Certificates
    41. 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
    42. Build a URL What are the allowed protocols? Where can I connect to? Make a Request How do I make a request? What are the restrictions on requests? Working with Request/Response Data How do I work with XML? How do I work with JSON?
    43. XmlReader/XmlWriter Linq to XML static void w_DownloadStringCompleted(object sender DownloadStringCompletedEventArgs e) { XElement x = XElement.Parse(e.Result); foreach (photo in x.Elements(\"photo\")) { //... } } XmlSerializer
    44. Pre-build a type using XML Attributes public class Photo { [XmlElement] public string photoName; [XmlElement] public string location; [XmlAttribute] public string size; } Serialize / Deserialize XmlSerializer xs = new XmlSerializer(typeof(Photo)); Photo p = (Photo) xs.Deserialize(myHttpResponseStream); string name = p.photoName; Requires manual work to build the type
    45. public class Video { Paste [XmlElement] public string author; [XmlElement] public string id; [XmlElement] public string title; [XmlElement] public string url; Copy } Functionality already available in XSD.EXE tool
    46. Build a URL What are the allowed protocols? Where can I connect to? Make a Request How do I make a request? What are the restrictions on requests? Working with Request/Response Data How do I work with XML? How do I work with JSON?
    47. “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 pages Smaller message size (but binary XML is a future possibility) Example: {“Person”:{“name”:”john”,”age”:42}}
    48. “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}]}
    49. Using the DataContractJsonSerializer public class Person { public string name; public int age; } Pre-build type, then deserialize and use {“Person”:{“name”:”john”,”age”:42}}
    50. … for RSS/Atom feeds
    51. RSS 2.0 Feeds Atom 1.0 Feeds Built-in Conform to Atom classes a Standard Publishing to work with (Future?) such services SyndicationFeed feed = SyndicationFeed.Load(…) foreach (SyndicationItem item in feed) { //Do something with item }
    52. Protocols RSS 2.0, Atom 1.0 Future possibility: Atom Publishing Protocol Essentially the same as in .NET 3.5 SyndicationFeed, 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
    53. <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>”
    54. Creating Services for Silverlight Creating and consuming WCF services Securing local services Creating public services (safe for cross-domain) Accessing Services that Describe Themselves “Add Service Reference” Accessing Services that Don’t Describe Themselves WebClient / HttpWebRequest, manual work Accessing Feeds RSS/Atom
    55. © 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.
    56. • Denial of Service • No protection (for now?) • Browser may hang if talking to malicious service •
    57. Timeline SL1.1 SL1.1 SL1.1 SL 2 SL 1.0 Alpha Alpha Dec CTP Beta1 Refresh • Demonstrated • Beta at MIX • Sep. 07 at MIX 07 07 • Shipped in Sep. 07 “Full” service consumption No service “Temporary” consumption story story (Consume ASP.NET AJAX services only) Nothing you will see today is “set in stone”
    58. Aside: Core vs. Extensions  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
    59. SOAP in Silverlight: Architecture and Extensibility Generated Proxy Generated Proxy (Complex) (Simple) Custom / User Proxy Runtime (Simple) Proxy Runtime (Complex) Code WCF Channel Stack Various Channels In Core User-defined In Extension Encoders Possible User-defined Textual XML Streaming Binary XML Transport Channels Extensibility User-defined HTTP(S) Duplex HTTP Duplex
    60. HTTP Stack Most services (SOAP, REST/POX, RSS/Atom feeds, …) accessable via HTTP   How it works: High-level components User code Web services proxies, Downloader control, E.g. POX … HttpWebRequest Browser Plugin APIs XmlHttpWebRequest IE/Firefox/Safari JavaScript Web Browser - Cookies, authentication info - Caching - Proxy server to use Windows/Mac Networking Layer
    61. Cross-Domain Calls: Service Opt-In: AJAX • 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
    62. SL app from InnocentMashups.com SL app from EvilGames.com http://financeData InnocentMashups.com Weather.com EvilApps.com How do we know when cross-domain access is safe? Rule of thumb: Can it be done without SL?
    63. Cross-Domain Restrictions Client Location SL app from Origin URL Origin URL Target URL • Only the target service knows if it’s safe to call it in a cross-domain way
    64. 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
    65. 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
    66. 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>
    67. Unsafe for Cross-Domain Client Location Relying on: Anything in the browser SL app from Origin URL Cookies Authenticated Sessions Zone (intranet) boundary Origin URL Target URL IP-address restrictions …
    68. 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
    69. 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
    70. 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 The .XAP package is just a renamed .ZIP file (other files…) ServiceReferences.clientConfig <endpoint address=“http://new.address.live.com” … /> (subset of WCF configuration)
    71. 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

    + goodfridaygoodfriday, 8 months ago

    custom

    1410 views, 0 favs, 0 embeds more stats

    Learn how easy it is to utilize POX, REST, RSS, ATO more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 1410
      • 1410 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 0
    • Downloads 10
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories