1. Yellow Pepper
Mobile Financial Solutions
Window Communication Foundation
August 2010
Presenter: Mai Phi Long
2. Agenda
– Overview
– WCF Architecture
– WCF Configuration and Hosting
– End Point (ABC)
– Contacts
– Binding
– Service Behaviors
– New features in WCF 4.0
4. WCF Design Goals
“The unified programming model for rapidly building service-
oriented applications on the Windows
Unifies today’s distributed technology
stacks
Unification
Composable functionality
Appropriate for use on-machine, in the
intranet, and cross the Internet
Productive Service-oriented programming model
Service-Oriented
Programming Supports 4 tenets of service-orientation
Maximized developer productivity
Interoperability & WS-* interoperability with applications running
Integration on other platforms
Interoperability with today’s distributed stacks
5. Unified Model
Enterprise
ASMX Services
Fast
Basic Secure
Open Binary
Interop Txns
Remotin
WSE g MSMQ
Secure Fast Queued
Open Secure Txns
Interop Binary
6. Before WCF
Remote Procedure Call
COM+
.NET Remoting
ASP.net web service
Hard code TCP Socket
MSMQ
…
8. Unified Model Benefits
Programming model
– Consistency
– Write less code when using multiple technologies
Flexibility
– Environments
• Productivity in development environment
• Simplify Automated Integration Testing
• Deployment options in production
– Design for distribution, run local
10. WCF Architecture
Application
… Error Metadata Instance
Service Model Behavior Behavior Behavior
Throttling Transaction Type Integ. Concurrency
Behavior Behavior Behavior Behavior
Messaging … Secure
Channel
Reliable
Channel
Text/XML
Encoder
HTTP TCP Queue Binary
… Channel Channel Channel Encoder
Hosting WAS ASP.NET WPF WinForm NT Service COM+
Environments
11. WCF Architecture: Messaging Runtime
Service Contract
Client and
Dispatcher Behaviors
Protocol(s) Protocol(s)
Encoder
Binding
Encoder
Transport Transport
Address
12. WCF Architecture: Composition & Behaviors
Formatter Transaction Security TCP
Behavior Behavior Channel Transport
Service
Code
Formatter Message Instancing Security TCP
Behavior Inspector Behavior Channel Transport
Service Model Layer Messaging Layer
Influences system operation Moves messages back and forth
based on incoming and
outgoing messages. and adds transfer semantics.
Effects of behaviors are local. Channels are symmetric.
13. Ways to Talk / Service Contract (MEPs)
One Way
Client Service
Request-Reply
Duplex (Dual)
One Way:
– Datagram-style delivery
Request-Reply
– Immediate Reply on same logical thread
Duplex
– Reply “later” and on backchannel (callback-style)
16. WCF Configuration and Hosting
WCF Service can be configured in code
WCF Service can be configured in XML or mix.
3 different ways to host WCF
– Self Hosting
– IIS Hosting
– Windows Service
17. Implement WCF in code
ServiceHost serviceHost = new ServiceHost(typeof(StockService),
new
Uri("http://localhost:8000/EssentialWCF"));
serviceHost.AddServiceEndpoint(
typeof(IStockService),
new BasicHttpBinding(),
"");
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(
typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexHttpBinding(),
"mex");
serviceHost.Open();
// The service can now be accessed.
Console.WriteLine("The services is ready. Press <ENTER> to
terminate.nn");
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
serviceHost.Close();
22. Endpoints
Client Service
Endpoint
Endpoint Message Endpoint
The service endpoint contains the information about the Address,
Binding, Contract, and Behavior required by a client to find and
interact with the service at this endpoint.
23. Address, Binding, Contract
Client Service
A B C
C B A Message A B C
Address Binding Contract
(Where) (How) (What)
24. How client knows WCF service mex
Metadata tells client how to connect & communicate to web service.
Design time, client sends request defined in WS-Metadata exchange standard and get
WSDL in return.
WSDL is then used to create proxy class and create config file at client
25. Expose mex endpoint by code or config file
httpGetEnabled allows client to query mex through Http Get method.
<system.serviceModel>
<services>
<service name="WCFServiceApplication.Service1"
behaviorConfiguration="WCFServiceApplication.Service1Behavior">
<endpoint address="" binding="wsHttpBinding"
contract="WCFServiceApplication.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFServiceApplication.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false
and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
26. Some tools to debug, and test WCF
WCF Test Client
WCF Service
Configuration
Editor
28. Three Types of Contracts
Service Contract => WSDL
– Maps the class methods of a .NET type to WSDL services, port types, and operations.
Operation contracts within service contracts describe the service operations, which
are the methods that implement functions of the service.
Data Contract => XSD
– Describe data structures that are used by the service to communicate with clients. A
data contract maps CLR types to XML Schema Definitions (XSD) and defines how
they are serialized and deserialized. Data contracts describe all the data that is sent
to or from service operations.
Message Contract => SOAP
– Map CLR types to SOAP messages and describe the format of the SOAP messages
and affect the WSDL and XSD definitions of those messages. Message contracts
provide precise control over the SOAP headers and bodies.
30. Synchronous vs Asynchronous Request Response
Main Thread
Service
BeginOperation
New Thread
EndOperation
client.AddCompleted += new EventHandler<MathPlayer.
MathService.AddCompletedEventArgs>(client_AddCompleted);
client.AddAsync(int.Parse(txtA.Text), int.Parse(txtB.Text));
31. Service Contract: OneWay
[ OperationContract(IsOneWay = true)]
void DoBigAnalysisFast(string ticker);
[OperationContract]
void DoBigAnalysisSlow(string ticker);
The client just needs acknowledgement of successful delivery; it does
not need an actual response from the service
32. Duplex Communication
Use wsDualHttpBinding
Since two endpoints
are used, we can define
two different bindings,
protocol for each
channels
33. Service Contract: Duplex Asymmetric
[ServiceContract(Session=true,
CallbackContract=typeof(ICalculatorResults)]
public interface ICalculatorProblems
{
[OperationContract(IsOneWay=true)]
void SolveProblem (ComplexProblem p);
}
public interface ICalculatorResults
{
[OperationContract(IsOneWay=true)]
void Results(ComplexProblem p);
}
34. Service Contract: Duplex Symmetric
[ServiceContract(Session=true,
CallbackContract=typeof(IChat)]
public interface IChat
{
[OperationContract(IsOneWay=true)]
void Talk(string text);
}
36. Data Contract
[DataContract]
public class ComplexNumber
{
[DataMember]
public double Real = 0.0D;
[DataMember]
public double Imaginary = 0.0D;
public ComplexNumber(double r, double i)
{
this.Real = r;
this.Imaginary = i;
}
}
37. Demo
Basic data type data contract
Class data type data contract
Hierarchy data type data contract
Collection data contract
38. Service Contract: Faults
[ServiceContract(Session=true)]
public interface ICalculator
{
[OperationContract]
[FaultContract(typeof(DivideByZero))]
ComplexProblem SolveProblem (ComplexProblem p);
}
try {
return n1 / n2;
}
catch (DivideByZeroException e) {
DivideByZero f = new DivideByZero (“Calculator”);
throw new FaultException<DivideByZero>(f);
}
39. Message Contract
[MessageContract]
public class ComplexProblem
{
[MessageHeader]
public string operation;
[MessageBody]
public ComplexNumber n1;
[MessageBody]
public ComplexNumber n2;
[MessageBody]
public ComplexNumber solution;
// Constructors…
}
41. Bindings & Binding Elements
Binding
HTTP Text Security Reliability TX
Transport Encoders Protocol
TCP HTTP Text Security Reliability
MSMQ IPC Binary TX .NET
Custom
Custom Custom
42. Standard Bindings in WCF.net 3.0
Binding Interop Security Session TX Duplex
BasicHttpBinding BP 1.1 N, T N N n/a
WSHttpBinding WS M, T, X N, T, RS N, Yes n/a
WSDualHttpBinding WS M RS N, Yes Yes
WSFederationBinding Federation M N, RS N, Yes No
NetTcpBinding .NET T, M T ,RS N, Yes Yes
NetNamedPipeBinding .NET T T, N N, Yes Yes
NetPeerTcpBinding Peer T N N Yes
NetMsmqBinding .NET T, M, X N N, Yes No
MsmqIntegrationBinding MSMQ T N N, Yes n/a
N = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions
43. New bindings in WCF.net 3.5
ws2007HttpBinding
ws2007FederationBinding
46. Reliability and Transactions
End-to-end Reliable messaging
– In-order guarantees
– Exactly once guarantees
Transport-Independent Sessions
– Integration with ASP.NET Sessions in IIS-Hosted
compatibility mode
Transactions
– Guaranteed atomic success or failure across services
47. Bindings & Behaviors: Reliable Sessions
Client Service
A B C
C B A A B C
A B C
Bindings provide
Session and
Guarantees
Reliable Messaging: in-order and exactly once (similar to
MSMQ and MQSeries guarantees).
48. Bindings & Behaviors: Transactions
Client Service
A B C
C B A A B C
A B C
Be
Be
Bindings Flow
Transactions
Behaviors
AutoEnlist and
AutoComplete
1- Multistep business process : Long running transaction WF integrates with
WCF
2- Short running transaction
52. Multiple EndPoints in a Service
Scenarior: SilverLight app can connect to basicHttpBinding
while WPF app can connect to wsHttpBinding. If we have one
service how can we serve two types of clients.
<service behaviorConfiguration="MathWCFServiceApplication.MathServiceBehavior"
name="MathWCFServiceApplication.MathService">
<!--EndPoint is used for WPF client-->
<endpoint name="wsHttpMath" address="ws" binding="wsHttpBinding"
contract="MathWCFServiceApplication.IMathService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!--EndPoint is used for SilverLight client-->
<endpoint name="basicHttpMath" address="basic" binding="basicHttpBinding"
contract="MathWCFServiceApplication.IMathService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
53. WCF returns JSON
JSON short for JavaScript Object Notation, is a lightweight computer data interchange
format. It is a text-based, human-readable format for representing simple data structures
and associative arrays (called objects).
<services>
<service name="Wcf2Ajax.Service1"
behaviorConfiguration="Wcf2Ajax.Service1Behavior">
<endpoint address="" behaviorConfiguration="AjaxBehavior"
binding="webHttpBinding" contract="Wcf2Ajax.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
55. Instance and Concurrent modes
WCF can control concurrency by the following two behaviors:
InstanceContextMode and ConcurrencyMode.
3 instance modes:
– Per-Session instance mode
– Per-Call instance mode
– Singleton Instance Mode
3 concurrent modes:
– Single - default setting. Instructs the runtime to allow access on one thread per
instance of the service class. This setting is the safest one because service
operations do not need to worry about thread safety.
– Reentrant - Only one thread at a time can access the service class, but the
thread can leave the class and come back later to continue.
– Multiple - Multiple threads may access the service class simultaneously. This
setting requires the class to be built in a thread-safe manner.
59. Service Throttling
maxConcurentInstances: controlling how many services can
be created by service. With this setting we are defining the
upper boundary of the number of instances resides in a
memory.
maxConcurentCalls: - controlling how many concurrent calls
can be active. What we can manage here is actually the
number of threads used in our service processing.
maxConcurrentSessions: - used to control how many active
sessions we have especially when using PerSession instance
mode.
60. WCF Security
Authentication
Authorization
Confidentiality
Integrity
Transport and Message Security
Please look at
http://wcfsecurityguide.codeplex.com/
62. StockTrader.net: a good WCF example
http://msdn.microsoft.com/en-us/netframework/bb499684.aspx
63. New features in WCF 4.0
Windows Communication Foundation (WCF) in .NET 4 includes three new
features areas.
1. Simplified Configuration
Simplifications to configuration make WCF easier to use. In WCF 4 we can create a
service without any configuration at all
2. Service Discovery
Service Discovery allows you to locate services on the same subnet using ad hoc
discovery, or using a proxy to establish connections with servers regardless of where
they are.
3. Service Routing
The Routing Service is designed to act as a generic, configurable SOAP intermediary.
It allows you to configure Content Based Routing, set up Protocol Bridging, and
handle communication errors that you encounter. The Routing Service also makes it
possible for you to update your Routing Configuration while the Routing Service is
running without restarting the service.
64. Demo
1. Simplified Configuration
2. Service Discovery
3. Service Routing
65. WCF Summary
WCF is good for SOA, distributed computing
It combines the best of all existing Microsoft distributed
computing stacks
It uses WS-* standards for interoperability and .NET value-
add for performance and integration with existing solutions
66. Good References
Book “Essential Windows Communication Foundation
for .NET 3.5”
PluralSight video training
http://www.pluralsight.com/main/screencasts/default.aspx
Channel 9
http://channel9.msdn.com/shows/Endpoint/
Speaker Notes These are what we refer to as the three pillars of WCF . They are the three design goals of WCF that really sum up what that technology is all about. They ’re what we’ll be drilling into for the remainder of this presentation. The first design goal is unification . When we talk about unification, we ’re talking about bringing together the various technologies available today for building distributed applications (COM+ and .NET Enterprise services, MSMQ, .NET Remoting, ASP.NET Web Services, Web Services Enhancements (WSE)) into a single, unified programming model. Why is this important? First, it reduces complexity by allowing us to focus on a single programming model rather than learn multiple programming models. Second, it allows us to compose/combine the functionality of today ’s technologies in ways that we can’t today. Finally, it allows us to use a single programming model for building distributed applications that communicate with one another on a single machine, across multiple machines, and across the Internet. The second design goal is interoperability and integration . We talk about interoperability and integration on two different pivots. First, WCF enables you to build services that speak advanced Web services protocols (WS-*), enabling your application to communicate with other WS-* compliant services running on other platforms. Second, we built WCF to provide a smooth upgrade and interop story for your distributed applications built on today ’s technologies (WSE, ASMX, .NET Enterprise Services, System.Messaging, .NET Remoting). Why are Interop and Integration important? First, the ability to communicate with applications running on other platforms provides you with the flexibility you need when working in a heterogeneous environment. Second, the ability to communicate with existing applications protects your investments and provides you with an optional, incremental upgrade path to WCF. The third design goal is all about productivity and service orientation . WCF provides developers with a highly productive programming model for building service-oriented applications. By using WCF ’s attribute-based programming to define your services, you can dramatically reduce the amount of code you write to build secure, reliable services. WCF also facilitates the development of applications that adhere to the “four tenets of service-orientation” that we’ll drill into later in the presentation. These tenets help ensure that your services are extremely flexible and resilient to change, thereby reducing long-term maintenance costs. Transition to next slide: We ’ll spend the rest of this presentation drilling into these 3 concepts, but before doing so, let’s quickly discuss some of the basics of WCF… 4 Tenets of service oriented: Boundaries Are Explicit Services Are Autonomous Services Share Schema and Contract, Not Class Service Compatibility Is Based Upon Policy
Consistency and Write less code when using multiple technologies: using System.ServiceModel for all distributed technologies in .NET 3.5 WCF, in .NET 2.0 using System.Runtime.Remoting for .net remoting, using System.Web.Service for web service …
Speaker Notes Here's a roll-up of everything we've been talking about. At the bottom of the WCF architecture, we have the hosting environments and service activation (How to spin up WCF services within a process) Above that we have the Messaging layer for moving messages around on the wire. One aspect of the Messaging layer that we didn ’t previously discuss is the message encoders. There are two types of Encoders for messages being sent from WCF services - Text/XML and Binary. If you use the HTTP protocol in conjunction with the Text/XML encoder, you get interoperability with other platforms. This is the default encoding/protocol combination. Of course, there are also optimizations that WCF services intelligently implement. For example, if an WCF service realizes that it’s communicating with another WCF service, it will use the Binary encoder to shrink packet size before sending it across the wire. The Service Model provides the API. Transition to next slide: Now that we ’ve discussed the first pillar of WCF (Unification of the architecture), let’s discuss the second – Interoperability and Integration…
Speaker Notes Let ’s take a closer look at how WCF services work using both the messaging layer and the Service Model. In this example, we ’ll see how incoming messages to an WCF service get processed before they reach our user code and then how outgoing messages get processed before being sent across the wire. We ’ll begin with the Messaging layer. The Messaging layer basically works by Taking messages in from the wire, Adding transfer semantics (called Channels ) Passing the messages on for additional processing. This flexible architecture allows you to chain multiple channels together. For example, if we want to send and receive our messages using the TCP transport, we have a channel called the TCP transport channel that allows you to do this. Once the TCP transport channel processes an inbound message, it simply hands off the message to next level in the processing chain. This “next level” could either be your application code or another channel . So if you want end-to-end interoperable SOAP-based security, you ’d simply stack a Security channel on top. This secures outbound messages before handing off to TCP and validates incoming messages before handing back to your application. From there we get to the Service Model layer. This layer bridges the gap between the messaging layer and our user code that implement the WCF service. Just as the messaging layer has the stackable concept of Channels, the Service model layer has a stackable concept called Behaviors. For example, there is a CLR Type Integration behavior. This takes an incoming message and figures out what method to call in order to dispatch it. In other words, this behavior takes an incoming XML Infoset - looks for "action=foo", "parameter=bar" and figures out what method to call. Of course, if you want, you can also just pass the message through to your code directly if you want to manipulate the XML yourself. The Transaction Behavior pulls the transaction out of the message and enlists in the transaction for you so when your code is called you are in the right transaction context. The Instancing Behavior allows you to choose if you want a new instance of your service with every call, or if you ’d like to use a singleton, as well as options that keep the same instance per session. Transition to next slide: There's a whole bunch of behaviors and channels. Let's look at them in action…
Note that boundaries are explicit. WCF will only publish methods that are decorated as part of the service. Note that this can be declared inline on a class instance as well. This does not require that the end user declare the service contract via an interface.
Demo: WCF\\03_OneWay
The operations of the contracts shown in the previous code examples accept only simple types as parameters and the return values are also simple types. If you are dealing with parameter lists of that sort, it is likely that you will—for the most part—ignore the fact that the data you are exchanging between services is serialized from its in-memory object representation into an XML information set and subsequently encoded for the wire transfer (and vice versa, of course). If you are dealing with predefined WSDL documents or if you want to use complex types as arguments, you need to give a little more consideration to the "data contract", however. While a service contract defines the shape and rules for interfaces (portTypes), along with their associated messages and operations, the data contract defines the shape and rules for the data that is exchanged through operation's input and output messages. The split between the data contract and the service contract is important. Service contracts typically define a logically and semantically related set of operations grouped on an interface and are about how a service behaves. The data contract defined information items that you flow across service boundaries and that are handled with additional logic on the provider and consumer side. If you were looking at it from a (English language) grammar perspective, you could consider operations to be the predicates and the data that flows are the objects , while the caller is the subject . Subjects can do a lot with objects. Every "do" is an operation.
Demo: WCF\\Contracts\\HRService
SO principles mean that designers should plan to exchange messages rather than procedure calls. The two styles of developing using WCF are RPC style where messages are generated using traditional procedure calls, but another mode of operation is available to users where they are cognizant of the messages being generated and want to control the SOAP encapsulation of the content that is being generated. Defining a message contract on a service means that the end user
Speaker Notes When we talk about reliable messaging (RM), we ’re talking about a guarantee that a message actually gets from one service to another (retrying on failed attempts until success). WCF supports two RM guarantees: in-order and exactly once (similar to MSMQ and MQSeries guarantees). “In order” guarantees ensure that messages received are done so in the order in which they are sent. Exactly once guarantees ensure that each message is received only once. There are also two modes for doing RM: an express lightweight mode in which messages are not stored to disk before sending; and a transacted mode in which messages are durably stored to disk before sending. In the case of machine failure, express mode services would lose any messages in the buffer at the time of failure. When you truly need classic, atomic two-phase commit across two services, WCF also supports transactions. This provides the ability to flow a transaction across service boundaries, for and all participants to enlist in the transaction, vote on the outcome, and succeed or fail together atomically. It ’s also important to point out that security, RM, and transaction support are all configured by default to communicate using Web Services specification-compliant protocols (WS-Security, WS-ReliableMessaging, WS-AtomicTransaction, etc). This provides a new level of integration between services built on our platform and built on other vendor's platforms (WebSphere, etc). Transition to next slide: Now that we ’ve discussed a broad range of WCF-supported features, let’s look at how WCF services are hosted and activated…
Demo: WCF\\GadgetDemo_WCFReturnJSON
Very good article http://mkdot.net/blogs/dejan/archive/2008/04/29/wcf-service-behaviors-instance-and-concurrency-management.aspx