2. • Introduction
• Basic Concepts
• Going deeper
• What's New in WCF 4/4.5
• Best Practices
• WCF Tools
• Use Cases
2
Agenda
yes, we can !
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 best
practices
• I have included as many links as possible
3
Introduction
Objectives
4. • WCF (CodeName Indigo) is a unified communication framework in.NET for
building 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 and
services 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 messages
4
Introduction
Why WCF ?
5. • To expose our first WCF service, we need
– An Endpoint (WCF’s ABC)
– A Service Implementation
– Some Config
– An Hosting Environnment
5
How to build our first WCF Service
(a very basic service )
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 Environment
6
ABC’s of WCF
Give me the A !
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 here
7
ABC’s of WCF
Give me the B !
8. • A Binding is an aggregate of micro WCF features
– Security, Duplex, Session, Encoding, Streaming, …
8
ABC’s of WCF
Give me the B !
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]
9
ABC’s of WCF
Give me the C !
11. • Services are designed to run in any Windows process that supports managed
code
– 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 here
11
WCF Hosting
How & where do I host my new WCF service ?
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 required
13
How to call this Service ?
WCF Clients
14. • An Automatic WCF Client in 2 clics
• Generate all client code, contract & configuration.
• Best suite if you don’t know the contract
14
WCF Clients
example #1 : Service Reference
15. • A little more code
• Perfect if you already know the
contract
15
WCF Clients
example #2 : ChannelFactory<T>
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 various
options 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 here
16
WCF Metadata
what is it ?
18. • WCF Supports 3 MEPs
– OneWay
Client sends a message using a fire and forget exchange. Like
UDP, it does not guarantee that the remote endpoint has received
the 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 the
return message is received. Classic pairs of Request-Response like
in HTTP GET method.
– Duplex
Like a phone conversation, both sides can send and receive
messages. Defined at contract level.
• Continue reading here
18
WCF Messaging
Message Exchange Patterns (MEP)
19. • In Connected Systems, there is no magic translation and data needs to be
exchanged 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 here
19
WCF Serialization
hidden part
21. • Scope of WCF Security
– Transfer security
Responsible for providing message confidentiality, data integrity, and authentication of
communicating parties
– Authorization
Responsible for providing a framework for making authorization decisions
– Auditing
Responsible 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 here
21
WCF Security
do not fear …
22. Transport Security
User credentials and claims are
passed using the transport layer
Interoperabable
Performant & Hardware Accelerated
o Transport-dependant
o Limited set of credentials
o Point to Point com only
22
WCF Security
Message Vs Transport Security
Message Security
User credentials and claims are
encapsulated in every message using
the WS-Security specification
end-to-end security
Partial/selective encryption and signing
Transport-independent
o Limited interoperability (WS-Security)
o Less performant
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 related
InstanceContext 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 the
same 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 23
WCF Concepts
Sessions, Instancing & Concurrency
24. • WCF is designed to solve the greater part of the
communication requirements, but there are
sometimes scenarios where the default behavior
is not valid.
• WCF is extensible by nature
– You can add or modify system behavior at every
level as you want
– Many shared concepts with AOP
• More than 25 interfaces to implement !
• Must-read blog post and here
24
WCF Extensibility
really powerfull !
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 Build
28
What’s new in WCF 4 /4.5 ?
All you need is here and here
29. WCF 3.0
29
What’s new in WCF 4 /4.5 ?
Simplified Configuration
WCF 4.5
Thanks to standard bindings and protocols mappings !
30. • Define and activate WCF services without having to maintain physical .svc
30
What’s new in WCF 4 /4.5 ?
File-less Activation
31. • A generic SOAP intermediary that acts
as a message router
• Features
– Content-based routing
• Header
• Body
– Priority Routing
– Protocol bridging
• Ex : HT¨TP to NetTcp
– Multicast
– Backup & Failover endpoints
– …
• Continue here
31
What’s new in WCF 4 /4.5 ?
Routing Service
33. • When invoking a service, a client should catch 3 types of exceptions
– TimeoutException
thrown when the time allotted for a process or operation has expired (on client or on server)
– CommunicationException
communication 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 here
33
WCF Best Practices
Exception Management & Fault Contracts
34. FaultContract is defined on each
operation
Service throws a Fault when there
is an handled/unhandled error
34
WCF Best Practices
FaultContracts sample
Client knows Faults (defined in
Contract) and can have specific
error management
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
– http://stackoverflow.com/questions/573872/
– http://msdn.microsoft.com/en-us/library/aa355056.aspx
35
WCF Best Practices
Dispose well, Padawan !
36. • Running a test against a running WCF service is not unit testing, but
integration 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, here
or here)
– Some workarounds when your service is using static class
OperationContext/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 code
36
WCF Best Practices
Unit Testing
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 changes
an operation might be added, or a data element in a message might be added or changed
=> breaking / non-breaking
– Address changes
a service moves to a different location where endpoints have new addresses
=> breaking
– Binding changes
a security mechanism changes or its settings change
=> breaking
– Implementation changes
when an internal method implementation changes
Non breaking
• Continue reading here
37
WCF Best Practices
Service Changes
38. • Contracts used by a client and by the service don’t require to be the
same
– 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 Versionning
Treat existing data contracts as immutable and create new ones with
unique qualified names.
• Lax Versionning
adding a new method, an optional member to the data contract will
not break existing clients.
Supported by WCF, but not by all clients
• Read the 15 tips here 38
WCF Best Practices
Contract Versionning
39. • Large set of performance counters to help you gauge your application's
performance
• Examples
– Service / Calls Per Second
– Service / Calls Faulted (Since restart)
– Operation / Call Duration
– EndPoint / Calls Failed Per Second
– …
• Activated by Config
• List of counters here
39
WCF Best Practices
Service Monitoring : Performance counters
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 Architecture
41
WCF Best Practices
AppFabric Monitoring
Monitoring Database
Dashboard
Custom
Tool
SQL Agent Job
WCF Events
Batch
Staging Table
WCF Events Table
DB Views
Server A
Runtime
WCF
EventCollector
Service
WCF
Server B
Runtime
WCF
EventCollector
Service
WCF
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 http://msdn.microsoft.com/en-us/library/bb552364.aspx
44
WCF Tools
WCFTestClient.exe
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 http://www.soapui.org/
46
WCF Tools
Soap UI
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.0AbinNETFX
4.0 Tools
• Integrated in Visual Studio
– Tools/WCF Service Configuration Editor
– Right Click on a WCF Service Project
• More Info here
48
WCF Tools
SvcConfigEditor.exe
50. • Simple GUI tool that helps us analyze diagnostic traces that are generated
by WCF service (when activated)
• Part of Windows SDK
– Located in C:Program Files (x86)Microsoft SDKsWindowsv8.0AbinNETFX
4.0 Tools
• Traces Files associated with .svclog (part of Windows SDK)
• More Info here
50
WCF Tools
SvcTraceViewer.exe
52. • Used to generate service model code from metadata documents and
metadata 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 here
52
WCF Tools
Svcutil.exe
54. • Toolset that facilitates the development of web
services using a schema first approach
• Features
– VS extension (Menu, Toolbars, …)
– A WSDL Wizard that allows to step through the
creation 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 supports
the selection of multiple XSD/WSDL source files
– …
• See project here
54
WSCF Blue
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 allotted
to this operation may have been a portion of a longer timeout."
56
Common Errors
Reader Quotas & Throttling
57. • Enums should always have a default value (=0)
– Code Analysis recomanded Rule
– Serialization : Enums are int, and default is 0
57
Common Errors
Enums
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 …
58
Use Cases
Is my service Up ?
59. • « I always have a error (404 or unreachable url) when I go to
http://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 Method
59
Use Cases
404 and unreachable service
60. • Event logging is enabled automatically by default, and there is no
mechanism 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 an
application. Examples include:
– Shared Listener: The WCF TCP Port Sharing Service logs an event when it fails
to start.
– Critical and error events, such as startup failures or crashes
– Message logging/tracing turned on/off: Logs events when message logging is
turned on/off. …
60
Use Cases
Service Startup