mastering advanced concepts in silverlight

74
Mastering advanced concepts in Silverligh t Level 300-400 Gill Cleere n Microsoft RD & MVP Ordina Belgium

Upload: microsoft-developer-network-msdn-belgium-and-luxembourg

Post on 17-May-2015

893 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Mastering advanced concepts in Silverlight

Mastering advanced concepts in SilverlightLevel 300-400

Gill CleerenMicrosoft RD & MVPOrdina Belgium

Page 2: Mastering advanced concepts in Silverlight

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

Page 3: Mastering advanced concepts in Silverlight

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

Page 4: Mastering advanced concepts in Silverlight

You can win

Tweet about this session using #techdaysBETelerik

and win one of the 3 Telerik RadControls for Silverlight licenses!

Page 5: Mastering advanced concepts in Silverlight

The duplex

story

Page 6: Mastering advanced concepts in Silverlight

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

Page 7: Mastering advanced concepts in Silverlight

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

Page 8: Mastering advanced concepts in Silverlight

Doing it yourself?

May not be a good idea!

Page 9: Mastering advanced concepts in Silverlight

Starring the HTTP Polling Duplex

Page 10: Mastering advanced concepts in Silverlight

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

Page 11: Mastering advanced concepts in Silverlight

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

Page 12: Mastering advanced concepts in Silverlight

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

Page 13: Mastering advanced concepts in Silverlight

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

Page 14: Mastering advanced concepts in Silverlight

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

Page 15: Mastering advanced concepts in Silverlight

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());

Page 16: Mastering advanced concepts in Silverlight

TRAIN INFORMATION USING HTTPPOLLINGDUPLEX

DEMO

Page 17: Mastering advanced concepts in Silverlight

Sockets

Page 18: Mastering advanced concepts in Silverlight

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

Page 19: Mastering advanced concepts in Silverlight

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

Page 20: Mastering advanced concepts in Silverlight

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)

Page 21: Mastering advanced concepts in Silverlight

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);

Page 22: Mastering advanced concepts in Silverlight

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

Page 23: Mastering advanced concepts in Silverlight

The Client (2)• Sockets callback execute on background thread

• Dispatcher.BeginInvoke() required to update UI

Page 24: Mastering advanced concepts in Silverlight

STOCK TICKER IN SILVERLIGHT USING SOCKETS

Demo

Page 25: Mastering advanced concepts in Silverlight

Let’s recapitulate...

• PollingDuplex• Http-based (using WCF)• Proxy generation

• Sockets• Faster• Not usable in all scenarios (port restrictions)• No WCF

Page 26: Mastering advanced concepts in Silverlight

NET.TCP BINDING

Page 27: Mastering advanced concepts in Silverlight

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

Page 28: Mastering advanced concepts in Silverlight

net.tcp performanceThroughput with net.tcp is 870 times faster than Polling Duplex

(Source Tomasz Janczuk)

Page 29: Mastering advanced concepts in Silverlight

net.tcp server scalabilityMany more clients can be connected at the same time with net.tcp

(Source Tomasz Janczuk)

Page 30: Mastering advanced concepts in Silverlight

STOCK TICKER IN SILVERLIGHT USING NET.TCP BINDING

Demo

Page 31: Mastering advanced concepts in Silverlight

Splitting your XAP using MEF

Page 32: Mastering advanced concepts in Silverlight

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

Page 33: Mastering advanced concepts in Silverlight

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

Page 34: Mastering advanced concepts in Silverlight

Recomposition• Application can be split into several XAPs• Can be loaded on demand using DeploymentCatalog• Main focus of MEF (next to being IOC)

Page 35: Mastering advanced concepts in Silverlight

Splitting your XAP

DEMO

Page 36: Mastering advanced concepts in Silverlight

SECURING COMMUNICATION OVER SERVICES

Page 37: Mastering advanced concepts in Silverlight

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

Page 38: Mastering advanced concepts in Silverlight

CHANGING TO HTTPSDEMO

Page 39: Mastering advanced concepts in Silverlight

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

Page 40: Mastering advanced concepts in Silverlight

SENDING IN CREDENTIALSDEMO

Page 41: Mastering advanced concepts in Silverlight

LEVERAGING ASP.NET AUTHENTICATION

Page 42: Mastering advanced concepts in Silverlight

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)

Page 43: Mastering advanced concepts in Silverlight

Application Services in ASP.NET(2)• Exposes

• Authentication• Roles• Profiles

Page 44: Mastering advanced concepts in Silverlight

ASP.NET AUTHENTICATION IN SILVERLIGHTDEMO

Page 45: Mastering advanced concepts in Silverlight

INavigationContentLoader

Page 46: Mastering advanced concepts in Silverlight

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

Page 47: Mastering advanced concepts in Silverlight

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);

}

Page 48: Mastering advanced concepts in Silverlight

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

Page 49: Mastering advanced concepts in Silverlight

INavigationContentLoaderDEMO

Page 50: Mastering advanced concepts in Silverlight

ADVANCED DATA BINDING IN SL5

Page 51: Mastering advanced concepts in Silverlight

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

Page 52: Mastering advanced concepts in Silverlight

ANCESTOR RELATIVESOURCE BINDINGDEMO

Page 53: Mastering advanced concepts in Silverlight

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

Page 54: Mastering advanced concepts in Silverlight

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(); }

Page 55: Mastering advanced concepts in Silverlight

BINDING TO DYNAMIC PROPERTIES WITH ICUSTOMTYPEPROVIDER

DEMO

Page 56: Mastering advanced concepts in Silverlight

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

Page 57: Mastering advanced concepts in Silverlight

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

Page 58: Mastering advanced concepts in Silverlight

USING MARKUP EXTENSIONS TO TRANSLATE AN APPLICATION

DEMO

Page 59: Mastering advanced concepts in Silverlight

DOWNLOADING AND UPLOADING FILES FROM SILVERLIGHT

Page 60: Mastering advanced concepts in 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

Page 61: Mastering advanced concepts in Silverlight

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>

Page 62: Mastering advanced concepts in Silverlight

DOWNLOADING AND UPLOADINGPICTURESFROM SILVERLIGHT

DEMO

Page 63: Mastering advanced concepts in Silverlight

VECTOR PRINTING WITH SILVERLIGHT

Page 64: Mastering advanced concepts in 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

Page 65: Mastering advanced concepts in Silverlight

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

Page 66: Mastering advanced concepts in Silverlight

VECTOR PRINTING WITH SILVERLIGHTDEMO

Page 67: Mastering advanced concepts in Silverlight

UNIT TESTING IN SILVERLIGHT

Page 68: Mastering advanced concepts in Silverlight

SL Unit Testing Framework• Compatible with regular unit testing framework• Part of SL Toolkit• Supports Assertions, Negative tests...

Page 69: Mastering advanced concepts in Silverlight

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();}

Page 70: Mastering advanced concepts in Silverlight

UNIT TESTING IN SILVERLIGHT

DEMO

Page 71: Mastering advanced concepts in Silverlight

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

Page 72: Mastering advanced concepts in Silverlight

Q&A

Page 73: Mastering advanced concepts in Silverlight

THANKS

Page 74: Mastering advanced concepts in Silverlight

© 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.