introduction to Windows Comunication Foundation
-
Upload
redaxe12 -
Category
Technology
-
view
3.487 -
download
1
description
Transcript of introduction to Windows Comunication Foundation
The Windows Communication Foundation
• Interoperability & IntegrationInteroperability & Integration
• Secure, Reliable, Transacted MessagingSecure, Reliable, Transacted Messaging
• Decoupled, Dynamic ApplicationsDecoupled, Dynamic Applications
The Connectivity ImperativeThe Connectivity Imperative
.NET At The Core.NET At The Core
Windows Communication FoundationWindows Communication Foundation
The Unified The Unified Framework For Framework For
Rapidly Building Rapidly Building
Service-Oriented Service-Oriented ApplicationsApplications
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
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
WS-* Protocol SupportWS-* Protocol Support
XMLXML
MessagingMessaging
SecuritySecurity TransactionsTransactionsReliable Reliable MessagingMessaging
Me
tad
ata
Me
tad
ata
SIDE-BY-SIDESIDE-BY-SIDE
InteropInterop
UPGRADEUPGRADE
Investment ProtectionInvestment Protection
SERVICE SERVICE ORIENTATIONORIENTATION
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
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
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
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
The Windows Communication 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
AgendaAgenda
• Introduction
• Overview• Main Concepts
• Hello World
• Contracts
• Bindings
• Behaviours
• Summary
Callers and ServicesCallers and Services
CallerCaller ServiceService
CallerCaller ServiceService
EndpointsEndpoints
EndpointEndpointEndpointEndpoint
EndpointEndpoint
EndpointEndpoint
ServiceService
CCBBAA
CCBBAA
CallerCaller
Address, Binding, ContractAddress, Binding, Contract
AABBCC
AddressAddress
Where?Where?
ContractContract
What?What?
BindingBinding
How?How?
CCBBAA
ServiceService
Service HostService Host
CallerCaller
Creating EndpointsCreating Endpoints
Proxy orProxy orChannelFactoryChannelFactory
AABBCC CCBBAA
CCBBAA
CCBBAA
proxy.csproxy.cs
CallerCaller
app/web.configapp/web.config
Exposing & Configuring EndpointsExposing & Configuring Endpoints
GetMetadataGetMetadata
WSDLWSDL
ServiceService
CCBBAA
CCBBAA
CCBBAA
CCBBAA
CCBBAA
CCBBAA
??
Hello WorldHello World
AgendaAgenda
• Introduction
• Overview
• Contracts• Service
• Data
• Message
• Bindings
• Behaviours• Instancing
• Summary
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
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);}}
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);}}
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)
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()); }}
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);
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);}}
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);}}
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);}}
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} }
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; } }}}
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} }
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…}}
AgendaAgenda
• Introduction
• Overview
• Contracts
• Bindings
• Behaviours
• Summary
Bindings & Binding ElementsBindings & Binding Elements
TransportTransport
IPCIPCMSMQMSMQ
CustomCustom
TCPTCP HTTPHTTP
ProtocolProtocolEncodersEncoders
.NET.NETTXTX
CustomCustom
SecuritySecurity ReliabilityReliability
BindingBindingHTTPHTTP TXTXSecuritySecurity ReliabilityReliabilityTextText
TextText
BinaryBinary
CustomCustom
TCPTCP
BinaryBinary
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]
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
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>
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>
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>
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
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
AgendaAgenda
• Introduction
• Overview
• Contracts
• Bindings
• Behaviours
• Summary
BehaviorsBehaviors
Client-Side Client-Side BehaviorsBehaviors
Service-SideService-SideBehaviorsBehaviors
ServiceService
CCBBAA
CCBBAA
CallerCaller
AABBCC
CCBBAA
BeBeBeBe
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
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
Example: TransactionsExample: Transactions
ServiceService
CCBBAA
CCBBAA
CallerCaller
AABBCC
CCBBAA
BeBe
Bindings Flow Bindings Flow TransactionsTransactions
Behaviors Behaviors AutoEnlist and AutoEnlist and AutoCompleteAutoComplete
Anti-Example:Anti-Example:Reliable SessionsReliable Sessions
ServiceService
CCBBAA
CCBBAA
CallerCaller
AABBCC
CCBBAA
Bindings Bindings provide provide
Session and Session and GuaranteesGuarantees
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…
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
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
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