Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Windows Communication Foundation (WCF)


Published on

Guided Tour on WCF for developers: basic concepts, what's new in WCF 4/4.5, best practices, WCF tools, use cases

Published in: Technology

Windows Communication Foundation (WCF)

  1. 1. WCFMaxime Lemaitre – 30/04/2013
  2. 2. • Introduction• Basic Concepts• Going deeper• Whats New in WCF 4/4.5• Best Practices• WCF Tools• Use Cases2Agendayes, we can !
  3. 3. • I won’t explain you every concepts & components of WCF • I will try to educate you to common WCF features and give you some bestpractices• I have included as many links as possible3IntroductionObjectives
  4. 4. • WCF (CodeName Indigo) is a unified communication framework in.NET forbuilding connected, service-oriented applications• Introduced in .Net 3.0– Before WCF : ASMX, Remoting, TcpServer, COM, POX…• Defines a common programming model and unified API for clients andservices to send messages between each other• Key characteristics– Service-oriented programming model (SOA):• Services are offered on an endpoint.• WCF completely separates service hosting, endpoints and services– Interoperability with non-WCF web services due to use of SOAP messages• WCF implements many of the WS-* standards– Extensibility• WCF client / server can be configured to interoperate with REST, ATOM-feeds, plain XML or JSON messages4IntroductionWhy WCF ?
  5. 5. • To expose our first WCF service, we need– An Endpoint (WCF’s ABC)– A Service Implementation– Some Config– An Hosting Environnment5How to build our first WCF Service(a very basic service )
  6. 6. • Address : « Where is my service ? »– The location of the service on the network where it can be reached• Some examples– http://localhost/calculatorservice.svc– net.msmq://localhost/private/calculatorservice– net.tcp://localhost:6000/calculatorservice• Set via configuration/code or inherited from Hosting Environment6ABC’s of WCFGive me the A !
  7. 7. • Binding : « How do I talk to this thing? »– The protocol/policies/settings used to connect to the service at it’s address• Some examples– Http(BasicHttp, WsHttp, WsDualHttp, WsFederation)– NetMsmq– NetNamedPipe– NetTcp– CustomBinding– …• Contains– Transport protocol (HTTP, TCP, MSMQ, …)– Message encoding (MTOM, XML, JSON, Binary, …)– Security / reliability settings (encryption & authentication)– …• All system provided binding are available here7ABC’s of WCFGive me the B !
  8. 8. • A Binding is an aggregate of micro WCF features– Security, Duplex, Session, Encoding, Streaming, …8ABC’s of WCFGive me the B !
  9. 9. • Contract : « What’s it going to do for me? »– Defines the operations, inputs, outputs, and mep of the service.• In WCF, a Contract is defined by an interface• A Contract defines– Grouping of operations in a service => .Net attribute [ServiceContract]– Signature of operations => .Net attribute [OperationContract]– Data types of operations => .Net attribute [DataContract]9ABC’s of WCFGive me the C !
  10. 10. 10Our first WCF Serviceon the road to Carl …
  11. 11. • Services are designed to run in any Windows process that supports managedcode– Hosting Options• Self-Hosting Fast & Flexible but not an enterprise solution• Windows Service Secure, Supported by all windows but lack of reliable features• IIS/WAS Components required but all advantages of IIS• IIS7 (Vista/WS2K8) introduced Windows Activation Service (WAS)– Host non HTTP protocols in IIS like Net.Tcp, NamedPipe, MSMQ…• Continue reading here11WCF HostingHow & where do I host my new WCF service ?
  12. 12. IIS Hosting12WCF HostingexamplesSelf- Hosting
  13. 13. • A WCF client is used to invoke a WCF Service– It’s not mandatory but will help you a lot (create SOAP manually ?)– Translate .Net code to SOAP and vice-versa– Logic-less implementation of Proxy Design Pattern• To create a WCF client, you need– An Address– A Binding– A Contract– Some code– (extra configuration & settings)• Clients have to be stateless and disposed when required13How to call this Service ?WCF Clients
  14. 14. • An Automatic WCF Client in 2 clics• Generate all client code, contract & configuration.• Best suite if you don’t know the contract14WCF Clientsexample #1 : Service Reference
  15. 15. • A little more code• Perfect if you already know thecontract15WCF Clientsexample #2 : ChannelFactory<T>
  16. 16. • WCF allows use to expose Metadata using standardized protocols– Metadata ?• Operations a client perform• The structure of the data types that the operations work with or return• Definitions of all the endpoints implemented by the service and the variousoptions needed for each such as security=> Basically, how to call the service• Two ways to expose Metadata– Mex Endpoint (for all services/bindings)– Wsdl/Disco (only for http Services)• Metadata is generally not exposed for production public service• More info here16WCF Metadatawhat is it ?
  17. 17. Http(s)GetEnabled17WCF Metadatahow to publish metadataIMexdataExchange
  18. 18. • WCF Supports 3 MEPs– OneWayClient sends a message using a fire and forget exchange. LikeUDP, it does not guarantee that the remote endpoint has receivedthe message . Defined at operation level. Warning : it’s not async !– Request-Reply (Default)Client sends a message to a WCF Service and then waits for a reply(no response = TimeOutException). Client stops processing until thereturn message is received. Classic pairs of Request-Response likein HTTP GET method.– DuplexLike a phone conversation, both sides can send and receivemessages. Defined at contract level.• Continue reading here18WCF MessagingMessage Exchange Patterns (MEP)
  19. 19. • In Connected Systems, there is no magic translation and data needs to beexchanged in a serialized form• WCF provides 2 Serializer– DataContractSerializer Opt-in Serialization• DataContract or Message Contract– XmlSerializer Opt-out Serialization=> 2 Serializers to handle all scenarios• There are also many ways to by-pass serialization– Using Stream object (for Streaming and Large Data)– Using Message class (Parsing Soap Message directly)• More info here19WCF Serializationhidden part
  20. 20. 20WCF SerializationexamplesDataContractSerializer(DataContract)DataContractSerializer(MessageContract)XmlSerializer
  21. 21. • Scope of WCF Security– Transfer securityResponsible for providing message confidentiality, data integrity, and authentication ofcommunicating parties– AuthorizationResponsible for providing a framework for making authorization decisions– AuditingResponsible for logging security-related events to the audit log• Basically WCF Security is managed by Security Configuration– None– Transport– Message– Both– TransportWithMessageCredential or TransportCredentialOnly• All bindings don’t provide the same security features !• Continue reading here and here21WCF Securitydo not fear …
  22. 22. Transport SecurityUser credentials and claims arepassed using the transport layer Interoperabable Performant & Hardware Acceleratedo Transport-dependanto Limited set of credentialso Point to Point com only22WCF SecurityMessage Vs Transport SecurityMessage SecurityUser credentials and claims areencapsulated in every message usingthe WS-Security specification end-to-end security Partial/selective encryption and signing Transport-independento Limited interoperability (WS-Security)o Less performant
  23. 23. • Sessions– A session is a correlation of all messages sent between two endpoints– this requires a binding that supports sessions• Instancing– Refers to controlling the lifetime of user-defined service objects and their relatedInstanceContext objects– Can be• Per Call : a new service object is created for each client request• Per Session : a new service object is created and maintained for each client session• Single : a service object handles all client requests• Concurency– Term given to the control of the number of threads executing in an InstanceContext at thesame time– Can be• Single : Maximum of one thread processing messages in the instance context at a time• Multiple : Can have multiple threads processing messages concurrently• Reentrant : The service instance is single-threaded and accepts reentrant calls (Duplex)• Continue reading here 23WCF ConceptsSessions, Instancing & Concurrency
  24. 24. • WCF is designed to solve the greater part of thecommunication requirements, but there aresometimes scenarios where the default behavioris not valid.• WCF is extensible by nature– You can add or modify system behavior at everylevel as you want– Many shared concepts with AOP• More than 25 interfaces to implement !• Must-read blog post and here24WCF Extensibilityreally powerfull !
  25. 25. 25WCF Extensibilitycaching for service operations using IOperationInvoker
  26. 26. • Transaction• Reliable Messaging• WCF REST• Queue Messaging• Streaming & Large Data• WCF Tracing• Async• Duplex Services• Workflow Services• Peer to Peer Networking• Syndication• WebSockets• …26Others FeaturesTo be continued …
  27. 27. What’s New in WCF 4 / 4.5 ?27
  28. 28. • WS-Discovery Support– Discovery Service– Announcement feature• Single WSDL Document• New Https Binding• WCF REST Improvements (deprecated)• Task-based Async/Await Support• New Configuration Default Values– Concurrent Calls/sessions/Instances, Net.Tcp settings, Timeouts• WebSocket Support– 2 new bindings : NetHttpBinding and NetHttpsBinding• WCF Configuration Tooltips & Validation on Build28What’s new in WCF 4 /4.5 ?All you need is here and here
  29. 29. WCF 3.029What’s new in WCF 4 /4.5 ?Simplified ConfigurationWCF 4.5Thanks to standard bindings and protocols mappings !
  30. 30. • Define and activate WCF services without having to maintain physical .svc30What’s new in WCF 4 /4.5 ?File-less Activation
  31. 31. • A generic SOAP intermediary that actsas a message router• Features– Content-based routing• Header• Body– Priority Routing– Protocol bridging• Ex : HT¨TP to NetTcp– Multicast– Backup & Failover endpoints– …• Continue here31What’s new in WCF 4 /4.5 ?Routing Service
  32. 32. WCF Best Practices32
  33. 33. • When invoking a service, a client should catch 3 types of exceptions– TimeoutExceptionthrown when the time allotted for a process or operation has expired (on client or on server)– CommunicationExceptioncommunication error in either the service or client application– FaultException/FaultException<TDetail>Represents a SOAP fault• SOAP-based applications use fault messages to notify processing error– “Exception” is not an unknown concept and not fully serializable– Do not throw ArgumentException/ArgumentNullException/… use Faults !• Exception details are not returned to client unless it has been activated– Can be a security risk because details expose internal service implementation– Use only on Dev• For global Exception handling, there is an IErrorHandler extensibility point• Continue reading here33WCF Best PracticesException Management & Fault Contracts
  34. 34. FaultContract is defined on eachoperationService throws a Fault when thereis an handled/unhandled error34WCF Best PracticesFaultContracts sampleClient knows Faults (defined inContract) and can have specificerror management
  35. 35. • Always Close the client proxy– Undisposed proxies can lead to memory leaks and random exceptions• Close = Dispose in WCF• Close/Dispose well– Close can throw exceptions• More info here–– Best PracticesDispose well, Padawan !
  36. 36. • Running a test against a running WCF service is not unit testing, butintegration testing.– Note : Testing WCF aspects is required because of all features (configuration,serialization, behaviors & extensitibility…)• To unit test your service, you should ignore the WCF aspect– Instantiate and invoke the service class directly– DI/IoC is possible in WCF using IInstanceProvider (see extensibility section, hereor here)– Some workarounds when your service is using static classOperationContext/WebOperationcontext (see here)• The best way to have unit tests is to design your service for testing– If your service code is all in the top-level class, then you wrote it to be untestable– The service class should be logic-less and be only a wrapper for your code36WCF Best PracticesUnit Testing
  37. 37. • In SOA, services and clients are autonomous– Service developers cannot assume that they control all clients– should be able to evolve service independent of its clients.• Four Categories of Service Changes– Contract changesan operation might be added, or a data element in a message might be added or changed=> breaking / non-breaking– Address changesa service moves to a different location where endpoints have new addresses=> breaking– Binding changesa security mechanism changes or its settings change=> breaking– Implementation changeswhen an internal method implementation changesNon breaking• Continue reading here37WCF Best PracticesService Changes
  38. 38. • Contracts used by a client and by the service don’t require to be thesame– they need only to be compatible• Versionning depends on the inner serializer (Datacontract,,XmlSerializer, ..), serialization attributes (mandatory, optional,order…) and schema validation (on/off)– 2 main approachs• Strict VersionningTreat existing data contracts as immutable and create new ones withunique qualified names.• Lax Versionningadding a new method, an optional member to the data contract willnot break existing clients.Supported by WCF, but not by all clients• Read the 15 tips here 38WCF Best PracticesContract Versionning
  39. 39. • Large set of performance counters to help you gauge your applicationsperformance• Examples– Service / Calls Per Second– Service / Calls Faulted (Since restart)– Operation / Call Duration– EndPoint / Calls Failed Per Second– …• Activated by Config• List of counters here39WCF Best PracticesService Monitoring : Performance counters
  40. 40. 40WCF Best PracticesPerformance counters integration in Centreon
  41. 41. • Auto Capture data generated by the execution of WCF Service– Call Duration, Errors, Faults, Exceptions, …– Data store implementation is a SQL Server database by default• Use Event Tracing for Windows (ETW)– Very limited impact on service– Async by nature• Monitoring Architecture41WCF Best PracticesAppFabric MonitoringMonitoring DatabaseDashboardCustomToolSQL Agent JobWCF EventsBatchStaging TableWCF Events TableDB ViewsServer ARuntimeWCFEventCollectorServiceWCFServer BRuntimeWCFEventCollectorServiceWCF
  42. 42. 42WCF Best PracticesAppFabric Monitoring
  43. 43. WCF Tools43
  44. 44. • Simple GUI tool that enables users to test a service• Can be standalone (without VS install)– For SysAdmins for example• Supported Features– Service Invocation: Request/Response and One-way message.– Bindings: all bindings supported by Svcutil.exe– Controlling Session.– Message Contract– XML serialization• Unsupported features– Duplex, Transaction, Streaming, Security/Authentication, Some bindings, …• Located at C:Program FilesMicrosoft Visual Studio 9.0Common7IDE• More info at ToolsWCFTestClient.exe
  45. 45. 45WCF ToolsWCFTestClient.exe
  46. 46. • A Soap Client for Http Service• Made in Java– Test exposed services outside MS envrionnement– Invoke other Soap Service• Features– Project Support– Follow Common WS-* Standard– Test Suite / Mock Service• Download free version at ToolsSoap UI
  47. 47. 47WCF ToolsSoap UI
  48. 48. • Simple GUI Config tool that Operates exclusively on<system.serviceModel> section• All WCF features in a GUI !• Output is guaranteed to comply with the WCF schema• Part of Windows SDK– Located in C:Program Files (x86)Microsoft SDKsWindowsv8.0AbinNETFX4.0 Tools• Integrated in Visual Studio– Tools/WCF Service Configuration Editor– Right Click on a WCF Service Project• More Info here48WCF ToolsSvcConfigEditor.exe
  49. 49. 49WCF ToolsSvcConfigEditor.exe
  50. 50. • Simple GUI tool that helps us analyze diagnostic traces that are generatedby WCF service (when activated)• Part of Windows SDK– Located in C:Program Files (x86)Microsoft SDKsWindowsv8.0AbinNETFX4.0 Tools• Traces Files associated with .svclog (part of Windows SDK)• More Info here50WCF ToolsSvcTraceViewer.exe
  51. 51. 51WCF ToolsSvcTraceViewer.exe
  52. 52. • Used to generate service model code from metadata documents andmetadata documents from service model– Example : Generate C# from an external Wsdl• Features– Generates code from running services or static metadata documents– Exports metadata documents from compiled code– Validates compiled service code– Downloads metadata documents from running services– Generates serialization code• More info here52WCF ToolsSvcutil.exe
  53. 53. 53WCF ToolsSvcutil.exe
  54. 54. • Toolset that facilitates the development of webservices using a schema first approach• Features– VS extension (Menu, Toolbars, …)– A WSDL Wizard that allows to step through thecreation of a WSDL from one or more XSDs– Data Contract Generator– A Service/Endpoint Stub (SVC) Generator– A Client Proxy Generator– A Generate Data Contract Code feature that supportsthe selection of multiple XSD/WSDL source files– …• See project here54WSCF Blue
  55. 55. Use Cases55
  56. 56. • To Prevent Denial of service (DoS) attacks, WCF have limits– ReaderQuotas constraints on the complexity of SOAP messages that can be processed“The maximum message size quota for incoming messages has been exceeded for the remote channel.See the server logs for more details.”– Throttling Throttling allows you to "smooth" out the load on the server"The open operation did not complete within the allotted timeout of 00:00:59.9989999. The time allottedto this operation may have been a portion of a longer timeout."56Common ErrorsReader Quotas & Throttling
  57. 57. • Enums should always have a default value (=0)– Code Analysis recomanded Rule– Serialization : Enums are int, and default is 057Common ErrorsEnums
  58. 58. • In WCF, there is no way to determine if service is up or down – Service down vs all calls are failed ?– WCF vs IIS ?– Client Timeouts/CommunicationExcetions vs Network failure ?• However, some questions :– Is IIS started ?– Is the application pool started ?– Are NetTcp/NamedPipe Services started ?– Is WAS Started ?– Is My service Activated ?• A ping/heartbeat method is sometimes a solution …58Use CasesIs my service Up ?
  59. 59. • « I always have a error (404 or unreachable url) when I go tohttp://yourservicedomain/myservice.svc. My service doesn’t work. »• Browsing svc file is not required to call the service– Sometimes Metadata is not published or accessible (because of Firewall)• It’s not because metadata is unreachable that you can’t invoke the service– Use WCF Test Client / Soap UI / Unit Test to call a Reag/Get Method59Use Cases404 and unreachable service
  60. 60. • Event logging is enabled automatically by default, and there is nomechanism to disable it in WCF• The Application Event Log contains most of the events generated by WCF.Most of the entries indicate that a particular feature failed to start up for anapplication. Examples include:– Shared Listener: The WCF TCP Port Sharing Service logs an event when it failsto start.– Critical and error events, such as startup failures or crashes– Message logging/tracing turned on/off: Logs events when message logging isturned on/off. …60Use CasesService Startup
  61. 61. 61Use CasesEvent Logs
  62. 62. Questions?62