You are on page 1of 70

Deepak Singhvi

Abans Technologies

Windows Communication Foundation (WCF 3.5) 07 Jun 2010

Agenda

Introduction Overview Contracts Bindings Behaviours Summary

Introduction

From Objects to Services

1980s

1990s

2000s

Object-Oriented
Polymorphism Encapsulation Subclassing

Component-Oriented
Location Transparent Tight Coupling Runtime Metadata

Service-Oriented
Message-based Schema+Contract+Policy Broad Interop

Four tenants of Service Orientation

Boundaries Are Explicit Services Are Autonomous Share Schema & Contract, Not Class Compatibility Based On Policy

SERVICE ORIENTATION

So Whats new
Unified Capabilities

Standards Support Programming Model Metadata


Client

Extensibility

Service

Windows Communication Foundation

INTEROPERABILITY

PRODUCTIVITY

SERVICE-ORIENTED DEVELOPMENT

Broad Support for WS* specifications Compatible with existing MS distributed application technologies

Unifies todays distributed technologies Attribute-based development Visual Studio 2005 integration

Enables development of loosely-coupled services Config-based communication

WCF

The next-generation platform for distributed systems A pillar of the Microsoft.NET Framework 3.0 Build WCF services in Visual Studio 2005 using any .NET Language

Intelligent code editing, IDE Extensions for WCF, debugging, refactoring, code snippets, etc. Microsoft Windows Vista Microsoft Windows XP Microsoft Windows Server 2003

Runs on

Codename Indigo

WCF Message based communication

Client

Service

Overview

What is WCF

Unification of Technologies

Abstraction of service code from the transport layer

Interoperability

WS-* specification support


Loose Coupling Configuration file based Attribute based

Service-Oriented Development

Developer efficiency

Widows Communication Foundation


Fast, Secure, Binary
ASMX .NET Remoting

Basic, Open Comm

Interop with other platforms

Extensibility Location transparency

AttributeBased Programming

Fast, Secure, Binary,Txns

Enterprise Services

WS-* Protocol Support

MessageOriented Programming
System.Messaging

Secure, Open Comm

WSE

MSMQ, Queued, Txns

Conventional Web Services


The old way of easily exposing components (ASMX):
.NET Component

ASMX Web Service

HTTP Client

WCF Services
The new way of easily exposing components (WCF):
.NET Component

Service Contract

HTTP Host

TCP Host

ICP Host

MSMQ Host

HTTP Client

TCP Client

ICP Client

MSMQ Client

WCF Standard Support ( Protocol support)

Security

Transacti ons

Messaging XML

Metada ta

Reliable Messagin g

Messaging (WS-Addressing):- SOAP is the fundamental protocol for web services. WS Addressing defines some extra additions to SOAP headers, which makes SOAP free from underlying transport protocol. One of the good things about Message transmission is MTOM, also termed as Message Transmission Optimization Mechanism. They optimize transmission format for SOAP messages in XML-Binary formant using XML optimized packaging (XOP). Because the data will sent in binary and optimized format, it will give us huge performance gain. Security (WS-Security, WS-Trust, and WS-Secure Conversation):- All the three WS- define authentication, security, data integrity and privacy features for a service. Reliability (WS-Reliable Messaging):- This specification ensures end-to-end communication when we want SOAP messages to be traversed back and forth many times. Transactions (WS-Coordination and WS-Atomic Transaction):- These two specifications enable transaction with SOAP messages. Metadata (WS-Policy and WS-Metadata exchange):- WSDL is a implementation of WSMetadata Exchange protocol. WS-Policy defines more dynamic features of a service, which cannot be expressed by WSDL.

Overall Architecture
Your code
objects behaviours channel channel channel
Metadata

Client

Service

XML formatting (ordered list of channel types & config)


config channel type 1 config channel type 2

Your code
behaviours channel channel channel

Binding

channel type N

config

encoding

Transport Channel (HTTP, TCP, MSMQ, Pipes, Peer) decoding

Main Goal

Unification

Unify todays distributed technology stacks Talk on-machine, cross-machine, cross-networks & Internet Codify best practices for building distributed apps Maximize productivity Interoperate with apps running on other platforms Integrate with Microsofts existing technologies

Productivity

Integration

Callers and Services

Caller

Service

Endpoints

Caller
Endpoint Endpoint Endpoint

Service

Endpoint

Address, Binding, Contract

Caller
A C B B B C C

Service
A
A

Address
Where?

Binding
How?

Contract
What?

ABCs of WCF Address, Binding, Contract


Three levels of abstraction expressed in WSDL Address Location of the service

Uri Can be dynamic Programmatic or config file based Interface based

Binding How to talk to the service

Contract What the service does

Creating Endpoints

Caller
A
C B A A A Proxy or ChannelFactory

Service
B
B B

C
C C

Service Host

Exposing & Configuring Endpoints


Caller GetMetadata
A B C

Service
A
A

WSDL
?

B
B

C
C

app/web.config

proxy.cs

A A

B B

C C

Address

Consists of:

Protocol Server Name Port Path

Logical address does not have map to a physical file, except in IIS

Contract

A collection of operations that specifies what the Endpoint communicates to the outside world Identified by Name and Namespace Duplex Contracts Server can call client WSDualHttpBinding Data and Service components There are three types of contracts Service Contracts Describe the operations a service can perform Map CLR types to WSDL Data Contracts Describes a data structure Maps CLR types to XSD Message Contracts Defines the structure of the message on the wire Maps CLR types to SOAP messages

Bindings

Specification of how the client and server will communicate Multiple endpoints possible for a service Predefined Bindings

Configuration file based

Custom Bindings

Predefined Bindings

BasicHttpBinding WSHttpBinding WSDualHttpBinding WSFederationBinding NetTCPBinding NetPeerTCPBinding NetNamedPipeBinding NetMsmqBinding MsmqIntegrationBinding

Creating a Service

Create the contract

Interfaces and implementations


Data Contracts Service Contracts

Host the service Configure bindings Create a client

Contracts

Service Contract

[ServiceContract] public interface ICalculator { [OperationContract] int DoMath(int a, int b, string op); }

Service Contract An Opt-In Model

[ServiceContract] public interface ICalculator { [OperationContract] int DoMath(int a, int b, string op); // Not exposed as part of the external contract :-) void MethodRequiredForImplementation(bool b);

Operations Types
Parameterized Operations
int DoParamsMath(int a, int b, string op);

Typed Message
MathResponse DoMsgMath(MathRequest msg);

Untyped (Universal)
Message DoXmlMath(Message m);

Service Contract: Names

[ServiceContract(Namespace="http://TechEd.WCF.Intro")] public interface IGreetings{ [OperationContract( Name=SayHello", Action="http://TechEd.WCF.Intro/HelloRequest", ReplyAction="http://TechEd.WCF.Intro/HelloResponse") string Greet(string name);

[OperationContractAttribute(Action = "*")] void UnrecognizedMessageHandler(Message msg);


}

Service Contract: Names

contd

class GreetingService : IGreetings { public string Greet(string name) { return Hello, " + name; } public void UnrecognizedMessageHandler(Message msg) { Console.WriteLine("Unrecognized message: " + msg.ToString()); }}

Modeling Request/Reply Operations


On the wire everything is asynchronous Therefore, Request and Reply correlation can be modeled in 2 ways It can be modeled either as a synchronous (blocking) method call

[OperationContract] MathResponse DoMsgMath(MathRequest msg);


or using the .NET Async-Pattern [OperationContract(AsyncPattern=true)] IAsyncResult BeginDoMsgMath(MathRequest msg, AsyncCallback cb, object state); MathResponse EndDoMsgMath(IAsyncResult call); The implementation on the client and the service can be different!

Service Contract: OneWay

[ServiceContract] public interface IOneWayCalculator { [OperationContract(IsOneWay=true)] void DoMath(MathRequest request); }

Service Contract: Duplex

[ServiceContract(SessionMode=SessionMode.Required, CallbackContract=typeof(ICalculatorResults)] public interface ICalculatorProblems { [OperationContract(IsOneWay=true)] void DoMath(MathRequest request); } public interface ICalculatorResults { [OperationContract(IsOneWay=true)] void DisplayResults(MathResponse response); }

Service Contract: Faults


[ServiceContract(Session=true)] public interface ICalculator{ [OperationContract] [FaultContract(typeof(MyMathFault))] int DoMath(int a, int b, string op);}

try{ return n1 / n2;} catch (DivideByZeroException e) { MyMathFault f = new MyMathFault (n1, n2); FaultReason r = new FaultReason("Divide By Zero"); throw new FaultException<MyMathFault>(f, r);}

Data Contract
[DataContract] public enum Position { [EnumMember] Employee, [EnumMember] Manager, [EnumMember(Value = Vendor")] Contractor, NotASerializableEnumeration }

Data Contract: Names


[DataContract(Name=Complex, Namespace=http://BigMath.Samples)] public class ComplexNumber { [DataMember(Name=RealPart)] public double Real = 0.0D; [DataMember(Name=ImaginaryPart)] public double Imaginary = 0.0D; public ComplexNumber(double r, double i) { this.Real = r; this.Imaginary = i; }

Data Contract: Enumerations


[DataContract] public enum Position { [EnumMember] Employee, [EnumMember] Manager, [EnumMember(Value = Vendor")] Contractor, NotASerializableEnumeration }

Message Contract
[MessageContract] public class ComplexProblem { [MessageHeader(Name="Op", MustUnderstand=true)] public string operation; [MessageBodyMember] public ComplexNumber n1; [MessageBodyMember] public ComplexNumber n2; [MessageBodyMember] public ComplexNumber solution;
// Constructors }

Bindings

Bindings & Binding Elements


Binding
HTTP Text Security
Reliability

TX

Transport
TCP
HTTP

Encoders
Text Binary Security

Protocol
Reliability

MSMQ

IPC

TX

.NET

Custom

Custom

Custom

Binding Element Features

Transport selection TCP, HTTP, Named Pipes, P2P, MSMQ, Custom Transport level security, Streaming Encoding Text, Binary, MTOM, Custom End-to-end Security Confidentiality, integrity, authN, authZ, Federation Credentials: X509, User/Pwd, Kerberos, SAML, InfoCard , Custom End-to-end Reliable messaging Transport independent QoS (in order, exactly once) Volatile and durable queues Transactions Shared transactions for synchronous operations Transactional queues for asynchronous operations [Your own feature goes here]

System-Provided Bindings
Binding BasicHttpBinding WSHttpBinding WSDualHttpBinding WSFederationBinding NetTcpBinding NetNamedPipeBinding NetPeerTcpBinding NetMsmqBinding MsmqIntegrationBinding Interop BP 1.1 WS WS Federation .NET .NET Peer .NET MSMQ Security N, T M, T, X M M T, M T T T, M, X T Session N N, T, RS RS N, RS T ,RS T, N N N N TX N N, Yes N, Yes N, Yes N, Yes N, Yes N N, Yes N, Yes Duplex n/a n/a Yes No Yes Yes Yes No n/a

N = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions

Binding in Config

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service serviceType="CalculatorService"> <endpoint address="Calculator" bindingSectionName="basicProfileBinding" contractType="ICalculator" /> </service> </services> </system.serviceModel> </configuration>

Configuring Bindings
<endpoint address="Calculator" bindingSectionName="basicHttpBinding" bindingConfiguration="UsernameBinding" contractType="ICalculator" /> <bindings> <basicHttpBinding> <binding name="UsernameBinding" messageEncoding="Mtom"> <security mode="Message"> <message clientCredentialType="UserName"/> </security> </binding> </basicHttpBinding> </bindings>

Custom Bindings
<bindings> <customBinding> <customBinding> <binding name="ReliableTCP"> <reliableSession inactivityTimeout="0:0:5 ordered="true"/> <binaryMessageEncoding/> <tcpTransport transferMode="Buffered"/> </binding> </customBinding> </customBinding> </bindings>

Choosing Bindings
WCF ASMX/WSE3 Other Platform
Any Binding

Any Protocol WS-* Protocols


WS-* Protocols

Any Binding

WCF WCF WCF

Http/WS Binding

Http/WS Binding

MSMQ COM+/ES
Moniker

MSMQ Protocol WS-* Protocols

MSMQ Binding

WCF
WCF

Interaction of Bindings and Code

Bindings provide features that affect code


Session Duplex Ordered Delivery Transaction Flow Queued Delivery

Attribute capture the codes requirements Infrastructure ensures that all the bindings satisfy these requirements

WCF Instance Creation

Following are different ways by which you would like to create WCF instances:

You would like to create new WCF service instance on every WCF client method call. Only one WCF service instance should be created for every WCF client session. Only one global WCF service instance should be created for all WCF clients.

To meet the above scenarios WCF has provided 3 ways by which you can control WCF service instances:

Per Call Per session Single instance

Per Call instance mode


[ServiceBehavior (InstanceContextMode = InstanceContextMode.Percall ] public class Service : IService { private int intCounter; public int Increment() { intCounter++ return intCounter; } }

Per session Instance mode

[ServiceBehavior (InstanceContextMode = InstanceContextMode.PerSes sion)] public class Service : IService { private int intCounter; public int Increment() { intCounter++ return intCounter; } }

Single Instance mode

[ServiceBehavior (InstanceContextMode = InstanceContextMode. Single )] public class Service : IService { private int intCounter; public int Increment() { intCounter++ return intCounter; } }

When should you use per call, per session and single mode?

Per call

You want a stateless services Your service hold intensive resources like connection object and huge memory objects. Scalability is a prime requirement. You would like to have scale out architecture . Your WCF functions are called in a single threaded model. You want to maintain states between WCF calls. You want ok with a Scale up architecture. Light resource references You want share global data through your WCF service. Scalability is not a concern.

Per session

Single

Behaviours

Behaviors
Caller
A
C Be B A A A

Service
B
B B

C
C C Be

Client-Side Behaviors

Service-Side Behaviors

Behaviors: Overview

Behaviors are all local Developers care about some behaviors Concurrency, instancing model, Everything that affects the correctness of the service Deployers care about other behaviors Throttling, Metadata exposure, message routing info, Everything that has to do with the services runtime aspects Anything you can do in config, you can do in code Code is King you can always override the config

Example: Security
Client
A C Be B A B C

Service
A
A

B
B

C
C

Be

Bindings Move Claims in Messages Behaviors Implement Security Gates Behaviors Provide Credentials

Example: Transactions
Caller
A C B A A A B B B C C C Be

Service

Bindings Flow Transactions Behaviors AutoEnlist and AutoComplete

Anti-Example: Reliable Sessions

Caller
A C B A A A B B B C C C

Service

Bindings provide Session and Guarantees

Behavior Features

Operation timeouts (close, open, idle) Concurrency, Instancing, Thread-Binding Throttling Faults, Exceptions Impersonation, Authorization, Auditing AutoEnlist, AutoComplete, Timeout, Isolation Serialization, MustUnderstand Metadata More

WCF Summary
Address
http://...

Binding
HTTP Transport WS-Security Protocol

Contract
Request/ Response

Behavior
Instancing Behavior Concurrency Behavior

net.p2p://...

Peer Transport TCP Transport NamedPipe Transport MSMQ Transport Custom Transport WS-RM Protocol

Throttling Behavior Metadata Behavior WS-AT Protocol Duplex Channel


Duplex One-Way

net.tcp://...

net.pipe://...

Error Behavior

Transaction Behavior

net.msmq://...

Custom Behavior

Security Behavior

xxx://...

Custom Protocol

Externally visible, per-endpoint

Opaque, per-service, endpoint, or op

WCF Application Architecture


Application
Messaging Services Queuing Service Model Instance Manager Channels Reliability Hosting Environments WAS IIS .exe Windows Service DllHost Transport Channels (IPC, HTTP, TCP) Message Encoder Security Context Manager Service Methods Type Integration Declarative Behaviors Transacted Methods Routing Eventing Discovery

Presentation Takeaways

WCF is the future of 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 WCF is available for Windows Vista, Windows XP SP2, Windows Server 2003

Thank You

deepak.singhvi@abanssecurities.com deepak.singhvi@gmail.com

You might also like