introduction to Windows Comunication Foundation

57

description

A good slide to to start working in WCF

Transcript of introduction to Windows Comunication Foundation

Page 1: introduction to Windows Comunication Foundation
Page 2: introduction to Windows Comunication Foundation

The Windows Communication Foundation

Page 3: introduction to Windows Comunication Foundation

• Interoperability & IntegrationInteroperability & Integration

• Secure, Reliable, Transacted MessagingSecure, Reliable, Transacted Messaging

• Decoupled, Dynamic ApplicationsDecoupled, Dynamic Applications

The Connectivity ImperativeThe Connectivity Imperative

Page 4: introduction to Windows Comunication Foundation

.NET At The Core.NET At The Core

Page 5: introduction to Windows Comunication Foundation

Windows Communication FoundationWindows Communication Foundation

The Unified The Unified Framework For Framework For

Rapidly Building Rapidly Building

Service-Oriented Service-Oriented ApplicationsApplications

Page 6: introduction to Windows Comunication Foundation

Windows Communication FoundationWindows Communication Foundation

INTEROPERABILITY PRODUCTIVITYSERVICE-ORIENTED

DEVELOPMENT

• Broad Support for WS-* specifications

• Compatible with existing MS distributed application technologies

• Unifies today’s distributed technologies

• Attribute-based development

• Visual Studio 2005 integration

• Enables development of loosely-coupled services

• Config-based communication

Page 7: introduction to Windows Comunication Foundation

InteropInteropwith otherwith otherplatformsplatforms

ASMX

Attribute- Attribute- BasedBased

ProgrammingProgramming

Enterprise Services

WS-*WS-*ProtocolProtocolSupportSupport

WSE

Message-Message-OrientedOriented

ProgrammingProgramming

System.Messaging

ExtensibilityExtensibilityLocation Location

transparencytransparency

.NET Remoting

Unified Programming ModelUnified Programming Model

Page 8: introduction to Windows Comunication Foundation

WS-* Protocol SupportWS-* Protocol Support

XMLXML

MessagingMessaging

SecuritySecurity TransactionsTransactionsReliable Reliable MessagingMessaging

Me

tad

ata

Me

tad

ata

Page 9: introduction to Windows Comunication Foundation

SIDE-BY-SIDESIDE-BY-SIDE

InteropInterop

UPGRADEUPGRADE

Investment ProtectionInvestment Protection

Page 10: introduction to Windows Comunication Foundation

SERVICE SERVICE ORIENTATIONORIENTATION

Page 11: introduction to Windows Comunication Foundation

From Objects to ServicesFrom Objects to Services

PolymorphismPolymorphismEncapsulationEncapsulationSubclassingSubclassing

Message-basedMessage-basedSchema+Contract+PolicySchema+Contract+PolicyBroad InteropBroad Interop

Location TransparentLocation TransparentTight CouplingTight CouplingRuntime MetadataRuntime Metadata

Object-Oriented Service-OrientedComponent-Oriented

1980s 2000s1990s

Page 12: introduction to Windows Comunication Foundation

SERVICE ORIENTATIONSERVICE ORIENTATION

Compatibility Based On PolicyCompatibility Based On Policy

Share Schema & Contract, Not Share Schema & Contract, Not ClassClass

Services Are AutonomousServices Are Autonomous

Boundaries Are ExplicitBoundaries Are Explicit

Four Tenets of Service OrientationFour Tenets of Service Orientation

Page 13: introduction to Windows Comunication Foundation

Conventional Web ServicesConventional Web Services

The old way of easily exposing components (ASMX):

.NET Component.NET Component

ASMX Web ServiceASMX Web Service

HTTP ClientHTTP Client

Page 14: introduction to Windows Comunication Foundation

WCF ServicesWCF Services

The new way of easily exposing components (WCF):

.NET Component.NET Component

HTTP HostHTTP Host TCP HostTCP Host ICP HostICP Host MSMQ HostMSMQ Host

HTTP ClientHTTP Client TCP ClientTCP Client ICP ClientICP Client MSMQ ClientMSMQ Client

Service ContractService Contract

Page 15: introduction to Windows Comunication Foundation

The Windows Communication Foundation

Page 16: introduction to Windows Comunication Foundation

Main Design GoalMain Design Goal

• Unification• Unify today’s distributed technology stacks

• Talk on-machine, cross-machine, cross-networks & Internet

• Productivity• Codify best practices for building distributed apps

• Maximize productivity

• Integration• Interoperate with apps running on other platforms

• Integrate with Microsoft’s existing technologies

Page 17: introduction to Windows Comunication Foundation

AgendaAgenda

• Introduction

• Overview• Main Concepts

• Hello World

• Contracts

• Bindings

• Behaviours

• Summary

Page 18: introduction to Windows Comunication Foundation

Callers and ServicesCallers and Services

CallerCaller ServiceService

Page 19: introduction to Windows Comunication Foundation

CallerCaller ServiceService

EndpointsEndpoints

EndpointEndpointEndpointEndpoint

EndpointEndpoint

EndpointEndpoint

Page 20: introduction to Windows Comunication Foundation

ServiceService

CCBBAA

CCBBAA

CallerCaller

Address, Binding, ContractAddress, Binding, Contract

AABBCC

AddressAddress

Where?Where?

ContractContract

What?What?

BindingBinding

How?How?

CCBBAA

Page 21: introduction to Windows Comunication Foundation

ServiceService

Service HostService Host

CallerCaller

Creating EndpointsCreating Endpoints

Proxy orProxy orChannelFactoryChannelFactory

AABBCC CCBBAA

CCBBAA

CCBBAA

Page 22: introduction to Windows Comunication Foundation

proxy.csproxy.cs

CallerCaller

app/web.configapp/web.config

Exposing & Configuring EndpointsExposing & Configuring Endpoints

GetMetadataGetMetadata

WSDLWSDL

ServiceService

CCBBAA

CCBBAA

CCBBAA

CCBBAA

CCBBAA

CCBBAA

??

Page 23: introduction to Windows Comunication Foundation

Hello WorldHello World

Page 24: introduction to Windows Comunication Foundation

AgendaAgenda

• Introduction

• Overview

• Contracts• Service

• Data

• Message

• Bindings

• Behaviours• Instancing

• Summary

Page 25: introduction to Windows Comunication Foundation

WCF ContractsWCF ContractsOverviewOverview

• 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

Page 26: introduction to Windows Comunication Foundation

Service ContractService Contract

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

Page 27: introduction to Windows Comunication Foundation

Service ContractService ContractAn Opt-In ModelAn Opt-In Model

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

// Not exposed as part of the external contract :-)// Not exposed as part of the external contract :-) void MethodRequiredForImplementation(bool b);void MethodRequiredForImplementation(bool b);}}

Page 28: introduction to Windows Comunication Foundation

Operations TypesOperations Types

MessageMessage DoXmlMath( DoXmlMath(MessageMessage m); m);

Untyped (“Universal”)Untyped (“Universal”)

MathResponseMathResponse DoMsgMath( DoMsgMath(MathRequestMathRequest msg); msg);

intint DoParamsMath( DoParamsMath(int a, int b, string opint a, int b, string op););

Typed MessageTyped Message

Parameterized OperationsParameterized Operations(shorthand for TM)(shorthand for TM)

Page 29: introduction to Windows Comunication Foundation

Service Contract: NamesService 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);}

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

Page 30: introduction to Windows Comunication Foundation

Modeling Request/Reply OperationsModeling 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

• or using the .NET Async-Pattern

• The implementation on the client and the service can be different!

[OperationContract][OperationContract]MathResponse DoMsgMath(MathRequest msg);MathResponse DoMsgMath(MathRequest msg);

[OperationContrac[OperationContract(AsyncPattern=true)t(AsyncPattern=true)]]IAsyncResult BeginDoMsgMath(MathRequest msg, IAsyncResult BeginDoMsgMath(MathRequest msg, AsyncCallback cb, object stateAsyncCallback cb, object state));;

MathResponse EndDoMsgMath(IAsyncResult call);MathResponse EndDoMsgMath(IAsyncResult call);

Page 31: introduction to Windows Comunication Foundation

Service Contract: OneWayService Contract: OneWay

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

Page 32: introduction to Windows Comunication Foundation

Service Contract: DuplexService Contract: Duplex

[ServiceContract(SessionMode=SessionMode.Required, [ServiceContract(SessionMode=SessionMode.Required, CallbackContract=typeof(ICalculatorCallbackContract=typeof(ICalculatorResultsResults))]]public interface ICalculatorProblemspublic interface ICalculatorProblems{{ [OperationContract(IsOneWay=true)][OperationContract(IsOneWay=true)] void DoMath(MathRequest request);void DoMath(MathRequest request);}}

public interface ICalculatorResultspublic interface ICalculatorResults{{ [OperationContract(IsOneWay=true)][OperationContract(IsOneWay=true)] void DisplayResults(MathResponse response);void DisplayResults(MathResponse response);}}

Page 33: introduction to Windows Comunication Foundation

Service Contract: FaultsService Contract: Faults

ttryry{{ return n1 / n2;return n1 / n2;}}catch (DivideByZeroException e)catch (DivideByZeroException e) {{ MyMathFault f = new MyMathFault (n1, n2);MyMathFault f = new MyMathFault (n1, n2); FaultReason r = new FaultReason("Divide By Zero");FaultReason r = new FaultReason("Divide By Zero"); throw new Faultthrow new FaultExceptionException<<MyMathFaultMyMathFault>(>(f, rf, r););}}

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

Page 34: introduction to Windows Comunication Foundation

Data ContractData Contract

[DataContract][DataContract]public enum Positionpublic enum Position{{ [[EnumMemberEnumMember]] Employee,Employee, [[EnumMemberEnumMember]] Manager,Manager, [[EnumMember(EnumMember(Value = Value = ““Vendor"Vendor"))]] Contractor,Contractor, NotASerializableEnumerationNotASerializableEnumeration} }

Page 35: introduction to Windows Comunication Foundation

Data Contract: NamesData Contract: Names

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

Page 36: introduction to Windows Comunication Foundation

Data Contract: EnumerationsData Contract: Enumerations

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

Page 37: introduction to Windows Comunication Foundation

Message ContractMessage Contract

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

Page 38: introduction to Windows Comunication Foundation

AgendaAgenda

• Introduction

• Overview

• Contracts

• Bindings

• Behaviours

• Summary

Page 39: introduction to Windows Comunication Foundation

Bindings & Binding ElementsBindings & Binding Elements

TransportTransport

IPCIPCMSMQMSMQ

CustomCustom

TCPTCP HTTPHTTP

ProtocolProtocolEncodersEncoders

.NET.NETTXTX

CustomCustom

SecuritySecurity ReliabilityReliability

BindingBindingHTTPHTTP TXTXSecuritySecurity ReliabilityReliabilityTextText

TextText

BinaryBinary

CustomCustom

TCPTCP

BinaryBinary

Page 40: introduction to Windows Comunication Foundation

Binding Element FeaturesBinding 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]

Page 41: introduction to Windows Comunication Foundation

System-Provided BindingsSystem-Provided Bindings

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 SessionsN = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions

Page 42: introduction to Windows Comunication Foundation

Binding in ConfigBinding in Config

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

Page 43: introduction to Windows Comunication Foundation

Configuring BindingsConfiguring Bindings

<endpoint address="Calculator"<endpoint address="Calculator" bindingSectionName=" bindingSectionName="basicbasicHttpHttpBindingBinding"" bindingConfiguration=" bindingConfiguration="UsernameBindingUsernameBinding"" contractType="ICalculator" /> contractType="ICalculator" />

<bindings><bindings> <basicHttpBinding> <basicHttpBinding> <binding name="<binding name="UsernameBindingUsernameBinding" " messageEncoding="Mtom">messageEncoding="Mtom"> <security mode="Message"><security mode="Message"> <message clientCredentialType="UserName"/><message clientCredentialType="UserName"/> </security></security> </binding></binding> </basicHttpBinding></basicHttpBinding><</bindings>/bindings>

Page 44: introduction to Windows Comunication Foundation

Custom BindingsCustom Bindings

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

Page 45: introduction to Windows Comunication Foundation

Choosing BindingsChoosing Bindings

WCFWCF WCFWCFAny ProtocolAny Protocol AnyAnyBindingBinding

AnyAnyBindingBinding

MSMQMSMQ WCFWCF

COM+/ESCOM+/ES WCFWCF

MSMQ MSMQ ProtocolProtocol

WS-* ProtocolsWS-* Protocols

MSMQMSMQBindingBinding

MonikerMoniker

ASMX/WSE3ASMX/WSE3 WCFWCFWS-* ProtocolsWS-* Protocols Http/WSHttp/WSBindingBinding

Other PlatformOther Platform WCFWCFWS-* ProtocolsWS-* Protocols Http/WSHttp/WSBindingBinding

Page 46: introduction to Windows Comunication Foundation

Interaction of Bindings and CodeInteraction of Bindings and Code

• Bindings provide features that affect code• Session

• Duplex

• Ordered Delivery

• Transaction Flow

• Queued Delivery

• Attribute capture the code’s requirements

• Infrastructure ensures that all the bindings satisfy these requirements

Page 47: introduction to Windows Comunication Foundation

AgendaAgenda

• Introduction

• Overview

• Contracts

• Bindings

• Behaviours

• Summary

Page 48: introduction to Windows Comunication Foundation

BehaviorsBehaviors

Client-Side Client-Side BehaviorsBehaviors

Service-SideService-SideBehaviorsBehaviors

ServiceService

CCBBAA

CCBBAA

CallerCaller

AABBCC

CCBBAA

BeBeBeBe

Page 49: introduction to Windows Comunication Foundation

Behaviors: OverviewBehaviors: 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 service’s runtime aspects

• Anything you can do in config, you can do in code• Code is King – you can always override the config settings

Page 50: introduction to Windows Comunication Foundation

Example: SecurityExample: Security

ServiceService

CCBBAA

CCBBAA

ClientClient

AABBCC

CCBBAA

BeBeBeBe

Bindings Move Bindings Move Claims in Claims in MessagesMessages

Behaviors Behaviors Implement Implement

Security GatesSecurity GatesBehaviors Behaviors Provide Provide

CredentialsCredentials

Page 51: introduction to Windows Comunication Foundation

Example: TransactionsExample: Transactions

ServiceService

CCBBAA

CCBBAA

CallerCaller

AABBCC

CCBBAA

BeBe

Bindings Flow Bindings Flow TransactionsTransactions

Behaviors Behaviors AutoEnlist and AutoEnlist and AutoCompleteAutoComplete

Page 52: introduction to Windows Comunication Foundation

Anti-Example:Anti-Example:Reliable SessionsReliable Sessions

ServiceService

CCBBAA

CCBBAA

CallerCaller

AABBCC

CCBBAA

Bindings Bindings provide provide

Session and Session and GuaranteesGuarantees

Page 53: introduction to Windows Comunication Foundation

Behavior FeaturesBehavior Features

• Operation timeouts (close, open, idle)

• Concurrency, Instancing, Thread-Binding

• Throttling

• Faults, Exceptions

• Impersonation, Authorization, Auditing

• AutoEnlist, AutoComplete, Timeout, Isolation

• Serialization, MustUnderstand

• Metadata

• More…

Page 54: introduction to Windows Comunication Foundation

Features SummaryFeatures Summary

AddressAddress BindingBinding BehaviorBehaviorContractContractHTTPHTTP

TransportTransport

TCPTCPTransportTransport

NamedPipeNamedPipeTransportTransport

MSMQMSMQTransportTransport

CustomCustomTransportTransport

WS-SecurityWS-SecurityProtocolProtocol

WS-RMWS-RMProtocolProtocol

WS-ATWS-ATProtocolProtocol

DuplexDuplexChannelChannel

CustomCustomProtocolProtocol

http://...http://...

net.tcp://...net.tcp://...

net.pipe://...net.pipe://...

net.msmq://...net.msmq://...

xxx://...xxx://...

ThrottlingThrottlingBehaviorBehavior

MetadataMetadataBehaviorBehavior

Error Error BehaviorBehavior

CustomCustomBehaviorBehavior

InstancingInstancingBehaviorBehavior

ConcurrencyConcurrencyBehaviorBehavior

TransactionTransactionBehaviorBehavior

SecuritySecurityBehaviorBehavior

Request/Request/ResponseResponse

One-WayOne-Way

DuplexDuplex

net.p2p://...net.p2p://...PeerPeer

TransportTransport

Externally visible, per-Externally visible, per-endpointendpoint

Opaque, per-service, endpoint, or Opaque, per-service, endpoint, or opop

Page 55: introduction to Windows Comunication Foundation

WCF Application “Architecture”WCF Application “Architecture”

ChannelsChannels

Transport ChannelsTransport Channels (IPC, HTTP, TCP…)(IPC, HTTP, TCP…)

Transport ChannelsTransport Channels (IPC, HTTP, TCP…)(IPC, HTTP, TCP…)ReliabilityReliabilityReliabilityReliability Message Message

EncoderEncoderMessage Message EncoderEncoder SecuritySecuritySecuritySecurity

Hosting EnvironmentsHosting Environments

Instance Instance ManagerManagerInstance Instance ManagerManager

Context Context ManagerManagerContext Context ManagerManager

TypeTypeIntegrationIntegration

TypeTypeIntegrationIntegration

ServiceServiceMethodsMethodsServiceService

MethodsMethodsDeclarativeDeclarativeBehaviorsBehaviors

DeclarativeDeclarativeBehaviorsBehaviors

TransactedTransactedMethodsMethods

TransactedTransactedMethodsMethods

WASWASWASWAS IISIISIISIIS .exe.exe.exe.exe WindowsWindowsServiceService

WindowsWindowsServiceService DllHostDllHostDllHostDllHost

Messaging Messaging ServicesServices

QueuingQueuingQueuingQueuing RoutingRoutingRoutingRouting EventingEventingEventingEventing DiscoveryDiscoveryDiscoveryDiscovery

Service Service ModelModel

ApplicationApplication

Page 56: introduction to Windows Comunication Foundation

Presentation TakeawaysPresentation 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

• Download WCF Today!• http://www.NetFx3.com/

• Presentation code at ShyCohen.com

Page 57: introduction to Windows Comunication Foundation