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.
4. Images
Sounds
Videos
RSS/Atom
Feeds
New services
you build
In-Browser Application
Existing
Intranet
services
Public
Internet
mashup APIs
5. Images
<XAML/> Sounds
Videos
1.0 RSS/Atom
Feeds
New services
you build
JavaScript
?
AJAX (XmlHttpRequest) Existing
Intranet
services
Public
Internet
mashup APIs
HTML
6. Images
Sounds
Videos
RSS/Atom
2 Feeds
New services
you build
Managed Code (C#/VB)
Existing
Intranet
services
Public
Internet
mashup APIs
HTML
10. 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
11. “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”…>
12. [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;
}
13. 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)
14. 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
•
15. 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…
}
16. All generated types/collections support data binding
•
Future Possibility:
•
Advanced data binding to services (XAML-only)
E.g. <GetProductsDataSource />
17. 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
•
18. 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)
19. 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
20. Images
Sounds
Videos
RSS/Atom
2 Feeds
New services
you build
Existing
Intranet
services
Public
Internet
mashup APIs
22. 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)
23.
24. 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…
25. 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
26. 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?
27. 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)
28. 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
29.
30. “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
33. “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)
34.
35. Code was exactly as in the regular
.NET Framework!
Good news for existing .NET developers
Some Silverlight-specific things to be aware of…
36. 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?
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. 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
39. 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?
40. 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
41. 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
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. 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
44. Silverlight exposes all HTTP features that the
browsers make available
Supported features are equivalent to Flash
45. 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
46. 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
47. 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?
48. XmlReader/XmlWriter
Linq to XML
static void w_DownloadStringCompleted(object sender
DownloadStringCompletedEventArgs e)
{
XElement x = XElement.Parse(e.Result);
foreach (photo in x.Elements(quot;photoquot;)) {
//...
}
}
XmlSerializer
49. 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
50. 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
51. 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?
52. “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}}
53. “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[“citiesquot;]
select new CityDisplay {Name = city[quot;namequot;],
Population = city[quot;populationquot;] };
{“cities”:[{“name”:”Vegas”,”population”:1000},
{“name”:”Seattle”,”population”:2000}]}
54. Using the DataContractJsonSerializer
public class Person
{
public string name;
public int age;
}
Pre-build type, then deserialize and use
{“Person”:{“name”:”john”,”age”:42}}
56. 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
}
57.
58. 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
60. 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
63. •
Denial of Service
•
No protection (for now?)
•
Browser may hang if talking to malicious service
•
64. 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”
65. 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
66. 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
67. 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
68. 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
69. 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?
70. 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
71. 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
72. 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
74. 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
…
75. 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
76. 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
77. 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)
78. 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