mastering advanced concepts in silverlight
TRANSCRIPT
Mastering advanced concepts in SilverlightLevel 300-400
Gill CleerenMicrosoft RD & MVPOrdina Belgium
About myself...
• Gill Cleeren• .NET Architect @Ordina (www.ordina.be) • Microsoft Regional Director• Silverlight MVP• Speaker (TechDays, TechEd, DevReach, DevDays, NDC Norway, Telerik
Usergroup tour Sweden, UK and Scotland...)• Visug user group lead (www.visug.be)• Author (Silverlight 4 Data and services cookbook)
• Silverlight 5 Data and Services Cookbook to be released in March• Blog: www.snowball.be• Email: [email protected] • Twitter: @gillcleeren
Session Contents• The duplex story• Using MEF to split up your XAP• Security• Custom navigation with the
INavigationContentLoader• Advanced data binding in Silverlight 5• Uploading and downloading files over a service• Vector printing in Silverlight• Unit testing with Silverlight Unit Testing Framework
You can win
Tweet about this session using #techdaysBETelerik
and win one of the 3 Telerik RadControls for Silverlight licenses!
The duplex
story
The duplex story• To push or to pull, that’s the question!• OK, push it’ll be!
• Scalable• Fast• Frequent client updates
• Sadly, HTTP is request/response
The duplex story• Silverlight offers 3 ways to do 2-way
communication:• Http Polling Duplex
• Since SL2, improved in SL3• TCP
• Since SL2• net.tcp
• Since SL4
Doing it yourself?
May not be a good idea!
Starring the HTTP Polling Duplex
HTTP Polling Duplex• Initiated by client• Based on smart polling
• Client polls server continuously on network layer• Server returns any queued messages and closes poll response
Creates the illusion of duplex communication
The binding• PollingDuplexHttpBinding inherits from
BasicHttpBinding• HTTP as transport• Net Duplex protocol• WS-Make Connection
• Replaces TCP or other duplex controls• Would require specific ports
Timeouts• Client polls continuously until
• there’s a message to transfer• a fault occurs• a timeout occurs
• PollTimeout defaults to 60 seconds• No exception is raised unless one party has aborted sends HTTP/1.1 200
message with no content• InactivityTimeout defaults to 10 minutes
• Occurs after 10 poll timeouts in a row
The service• Similar to regular WCF service
• Defines 2 contracts• Regular contract• CallbackContract
• IsOneWay=true • Ensures clients won’t wait for response
• GetCallbackChannel<T>()• Manages Faults in case a client is disconnected
The service• Works as a thread that receives its updates from
source (DB, XML, FileSystemWatcher...)• Upon changes of the source, all clients should be notified
• Can be hosted in • IIS• Windows Service• Any app really
The client
• Create a proxy from Visual Studio• Create binding that is compatible with server
binding
• Register with the service• No need to marshal to UI thread
CustomBinding binding = new CustomBinding(new PollingDuplexBindingElement(), new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement());
TRAIN INFORMATION USING HTTPPOLLINGDUPLEX
DEMO
Sockets
Sockets
• System.Net.Sockets • Endpoints on both sides
• “Real” duplexing• Since SL4, support for UDP multicast
• Uses pure TCP communication• HTTP is layer on top of TCP, thus slower
• Big disadvantages:• Can only use ports between 4502 and 4534
• Not good for internet scenarios• Lots of manual work• Needs seperate policy server
The Policy Server• Follows cross-domain restrictions
• Server will not be web server won’t serve policy file
• PolicyServer is required• Can be any type of app
• TcpListener waits for incoming request at port 943
The Policy Server• No policy check is performed if running as trusted
application (SL4 and SL5 only)• SL4 allows policy calls to be made over HTTP
• If the call to HTTP fails, it will not check again on port 943 though!
• SocketAsyncEventArgs.SocketClientAccessPolicyProtocol• Http• Tcp (default)
Socket server• Also uses TcpListener for incoming requests• Maintains list of clients
• Loop over List<StreamWriter> and send data to each client
• Can only listen on ports between 4502 and 4534
tcpListener.BeginAcceptTcpClient(OnBeginAcceptTcpClient, null);
The Client
• Clients can• connect (ConnectAsync())• send data (SendAsync())• receive data (ReceiveAsync())
• Use Socket class to communicate• TcpClient class is not available in Silverlight
• Use SocketAsyncEventArgs• Used to
• define asynchronous callback methods • Pass user state (UserToken) between these methods
• Socket object
The Client (2)• Sockets callback execute on background thread
• Dispatcher.BeginInvoke() required to update UI
STOCK TICKER IN SILVERLIGHT USING SOCKETS
Demo
Let’s recapitulate...
• PollingDuplex• Http-based (using WCF)• Proxy generation
• Sockets• Faster• Not usable in all scenarios (port restrictions)• No WCF
NET.TCP BINDING
net.tcp binding
• SL4 introduces the net.tcp binding• Not only BasicHttpBinding• Allows for duplex communication as well
• It is• Fast• Based on WCF
• Integrates with Visual Studio• Built on top of TCP
• Same restrictions on available ports• Usable for intranet environments
• Not supporting SSL • Combination of faster communication and easy programming
model
net.tcp performanceThroughput with net.tcp is 870 times faster than Polling Duplex
(Source Tomasz Janczuk)
net.tcp server scalabilityMany more clients can be connected at the same time with net.tcp
(Source Tomasz Janczuk)
STOCK TICKER IN SILVERLIGHT USING NET.TCP BINDING
Demo
Splitting your XAP using MEF
XAP on-demand• Try to get your app “running” as quickly as possible
Bring down initial download sizeXAP partitioning and on-demand loading
• Several ways to implement• INavigationContentLoader• Prism (modularity)• MEF
XAP on-demand• MEF has concept of
• Parts (Imports and exports)• Catalogs (contain other catalogs and parts)
• MEF creates composition • Can change over time recomposition
• New catalogs (parts) become available
Recomposition• Application can be split into several XAPs• Can be loaded on demand using DeploymentCatalog• Main focus of MEF (next to being IOC)
Splitting your XAP
DEMO
SECURING COMMUNICATION OVER SERVICES
Securing communication• No wsHttpBinding in Silverlight 5
• Was in planning, didn’t make the cut• When accessing services, we should be able to verify
the user• Information can be intercepted
• One solution is using SSL for communication• Requires changes to IIS (built-in server does not support SSL)• Use HttpsTransport in WCF config• Service reference will now use https
CHANGING TO HTTPSDEMO
Securing communication (2)
• Not all services are publicly available• Require message-based security
• Sending username/password combination in message• Full message-based security is not supported since SL
does not support WsHttpBinding
SENDING IN CREDENTIALSDEMO
LEVERAGING ASP.NET AUTHENTICATION
Application Services in ASP.NET• The ASP.NET Membership API is exposed over
Application Services (since ASP.NET 3.5)• Silverlight and ASP.NET Ajax can both benefit from these• Needs to be enabled (disabled by default)
• Allows us to re-use existing membership to integrate Silverlight in existing ASP.NET applications
• Required to add *.svc file (service endpoint)
Application Services in ASP.NET(2)• Exposes
• Authentication• Roles• Profiles
ASP.NET AUTHENTICATION IN SILVERLIGHTDEMO
INavigationContentLoader
INavigationContentLoader• Silverlight 3 introduced the Navigation Application
template• Silverlight 4 added an extensibility point to this: the
INavigationContentLoader• Developers can handle the page-loading process• You get context on what to load (the targetUri)• You get to do whatever you want with this
INavigationContentLoader• Provides cancellable asynchronous pattern for
loading content based upon a target Uri• We can set our own content loader on the Frame• SL will not use the default anymore
(PageResourceContentLoader)public interface INavigationContentLoader {
IAsyncResult BeginLoad(Uri targetUri, Uri currentUri, AsyncCallback userCallback, object asyncState);
void CancelLoad(IAsyncResult asyncResult); bool CanLoad(Uri targetUri, Uri currentUri); LoadResult EndLoad(IAsyncResult asyncResult);
}
Useful or not?
• YES!• Use it in MVVM scenarios to link the View and the
ViewModel• Use it to pass constructors parameters• Use it to load stuff before navigating to a page (load data
from a service)• Use it to navigate to pages in other XAPs (download the
XAP on demand...)• Use it to authenticate the request• Use it to handle navigation errors
INavigationContentLoaderDEMO
ADVANCED DATA BINDING IN SL5
Ancestor RelativeSource
• A feature available in WPF and added in Silverlight 5• Previously, difficult to access properties of parent element from
within a template• With new feature, possible to access elements in the visual tree
outside of a template• Know exactly how many parents to traverse?
• AncestorLevel
• Typical places where you’ll use this:• Hiding/showing an element in a ListBox ‘s ItemTemplate based on the parent
property• ComboBox ‘s ItemsSource needs to access DataContext outside the
ItemTemplate
ANCESTOR RELATIVESOURCE BINDINGDEMO
Binding to Dynamic Properties with ICustomTypeProvider
• Up until Silverlight 4, when the properties of a type used in data-binding, we needed to recompile
• With Silverlight 5, the ICustomTypeProvider was added• Enables binding to an object of which the structure isn’t
known until runtime• Happens when working with XML/JSON coming from a
service
Binding to Dynamic Properties with ICustomTypeProvider
• ICustomTypeProvider supports adding properties on-the-fly
• Interface is quite simple:
• We need to return our own Type• SL data-binding checks if object implements the interface• If it does, it uses custom type in the binding
public interface ICustomTypeProvider { public Type GetCustomType(); }
BINDING TO DYNAMIC PROPERTIES WITH ICUSTOMTYPEPROVIDER
DEMO
Markup extensions• A markup extension is a way for the parser to know
that an object, attached to the ‘normal’ object graph is to be created• Text={Binding SomeValue}
• A markup extension can be recognized by the {...} that surround it
• In Silverlight 4, only a few exist• Binding, StaticResource
Custom markup extensions
• Allow us to extend XAML• We can instruct to run custom logic from custom markup
extensions• Already existed in WPF• Typical uses:
• Automatic translations• Avoiding use of converters or code in ViewModel• Static class instantiation from XAML
USING MARKUP EXTENSIONS TO TRANSLATE AN APPLICATION
DEMO
DOWNLOADING AND UPLOADING FILES FROM SILVERLIGHT
Sending files over the wire• Sometimes more than just data is required
• Sending files over the network• Ex: Silverlight Image Editor application, where the finished
application needs to be uploaded to the server• Data needs to be converted into binary data
• File needs to be converted to binary data• Send it over the wire• Re-convert back into file
Sending files over the wire• Configuration change required<bindings> <basicHttpBinding> <binding name="ImageUploadBinding"
maxReceivedMessageSize="2000000" maxBufferSize="2000000">
<readerQuotas maxArrayLength="2000000" maxStringContentLength="2000000“
/> </binding> </basicHttpBinding></bindings>
DOWNLOADING AND UPLOADINGPICTURESFROM SILVERLIGHT
DEMO
VECTOR PRINTING WITH SILVERLIGHT
Vector-based printing• Silverlight 4 introduced printing
• Bitmap-based• Caused printers to receive way too much data• Only OK for 2-3 pages (reports, screen dump...)
• Silverlight 5 adds PostScript printing• Still using same classes: PrintDocument• Still using same events: PrintPage, BeginPrint, EndPrint
Vector-based printing• SL5 adds PrinterFallbackSettings class
• Can be used by Print()• 2 options:
• ForceVector• OpacityTreshold
• If printing element with opacity != 1, SL5 will default to bitmap printing
• ForceVector will overrule, defaulting to vector printing, even if incompatible elements are found
• OpacityTreshold tells SL for which value it can default to opacity = 1.0
VECTOR PRINTING WITH SILVERLIGHTDEMO
UNIT TESTING IN SILVERLIGHT
SL Unit Testing Framework• Compatible with regular unit testing framework• Part of SL Toolkit• Supports Assertions, Negative tests...
Async testing• What if we need to test calling a service?
• This is async in Silverlight• Solution:
• Have test derive from SilverlightTest base class• Add Asynchronous attribute on the test method• Use the Enqueue* methods to queue async calls
[TestMethod][Asynchronous]public void AsyncTests(){ EnqueueCallback(() => Assert.IsTrue(true)); EnqueueTestComplete();}
UNIT TESTING IN SILVERLIGHT
DEMO
Session Summary• Advanced service scenarios possible from Silverlight
• Duplex• HttpWebRequest• File uploads
• Communication can be secured and debugged• Re-use existing authentication• Unit Testing for more robust applications
Q&A
THANKS
© 2012 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.