Windows Communication Foundation Giovanni Della-Libera Principal Software Design Engineer Connected Systems Division Microsoft Corporation
[email protected]
Windows Comm. Foundation Product Information Part of WinFX
WinFX = .NET 2.0 + WCF + WF + WPF + “InfoCard” A set of extensions to the .NET Framework 2.0
Build WCF clients and services in Visual Studio 2005 using any .NET Language Intelligent code editing, IDE Extensions for WCF, debugging, refactoring, code snippets, … Visual Basic .NET, C#, …
Runs on
Windows XP Windows Server 2003 Windows Vista
Windows Comm. The unified programming model for Foundation rapidly building service-oriented
rapidly building service-oriented applications on the Windows platform
Unification
• Unifies today’s distributed technology stacks • Appropriate for use on-machine, crossmachine, and across Internet
Service Orientation
• Codifies best practices for building distributed applications • Maximizes productivity
Integration
• Interoperates with applications running on other platforms • Integrates with our own distributed stacks
From Objects to Services
In Search of Better Application Building Blocks Object-Oriented 1980s
Encapsulation Polymorphism Subclassing
Component-Oriented 1990s
Dynamic Loading Interface-based Runtime Metadata
Service-Oriented 2000s
Message-based Schema+Contract Binding via Policy
Service Orientation Key Concepts
Applications
Operational Requirements
State composed of
enforce Policies
have
governed by
manage
Services
bound by
exchange Message Exchange Pattern
Contracts
describe
made of
Messages is a set of
Schemas
define structure of
Endpoints Client Endpoint Endpoint
Endpoint Endpoint
Service
Address, Binding, Contract Client C
B
A
A
B
C
A
B
C
A
B
C
Service
Address
Binding
Contract
Where?
How?
What?
Creating Endpoints Client A
B
C
A
A
B
C
ChannelFactory
A
B
C
C
B
ServiceHost
Service
Service Configuration
<system.serviceModel> <services> <service name="HelloService"> <endpoint address="http://localhost/HelloService" binding="basicHttpBinding" contract="IHello" />
Contracts [ServiceContract] public interface IHello { [OperationContract] string Hello(string name); } public class HelloService : IHello { public string Hello(string name) { return “Hello, ” + name; } }
Describing the Contract Ties together multiple operations wsdl:portType wsdl:operation
Describes the service operation
[ServiceContract] public interface MyContract { [OperationContract] MyReply MyOp(MyRequest request);
}
[OperationContract] void MyOp2(MyRequest2 request);
Operations Types Operations w/ Parameters
(shorthand for TM)
Typed Message Untyped (“Universal”)
void Buy( ItemInfo info, int amount );
void Buy( MyRequest msg );
void Buy( Message m );
Describing the Message Format wsdl:message wsdl:part
xsd:element
[MessageContract] public class MyRequest { [MessageHeader] public int Amount; [MessageBody] public ItemInfo Info; } [DataContract] public class ItemInfo [DataMember] public [DataMember] public [DataMember] public }
{ int ID; double Cost; string Name;
Message Exchange Patterns Request/Repl [OperationContract] y
One Way
Duplex
string Echo(string text);
[OperationContract(IsOneWay = true)] void LogIt(DateTime stamp, string str);
[ServiceContract(CallbackContract=typeof(IChat)] public interface IChat { [OperationContract(IsOneWay = true)] void Chat(string text); }
Session
[ServiceContract(SessionMode= SessionMode.Required)] public interface IConnection { … }
Controlling Message Dispatch SOAP messages have Actions <wsa:Action>http://tempUri.org/IFoo/Bar
Operations are matched to Actions Implicitly or Explicitly [OperationContract] Message2 Foo(Message1 request); [OperationContract( Action = "http://tempUri.org/IFoo/Foo", ReplyAction = "http://tempUri.org/IFoo/FooReply" )] Message2 Foo(Message1 request);
The Universal Contract "*" matches all actions [OperationContract(Action = “*”)] Message ProcessMessage(Message request);
• No nice CLR objects to work with • Useful when you don’t care to process the content of the message •
E.g. routing, pub/sub, etc.
Request/Reply and On the wire everything is asynchronous Async Correlation of Request and Reply messages can be modeled either as a synchronous method call [OperationContract] Message2 Chat(Message1 request);
or using the .NET Async-Pattern
or using the .NET Async-Pattern [OperationContract(AsyncPattern=true)] IAsyncResult BeginChat(Message1 request, AsyncCallback cb, object state); Message2 EndChat(IAsyncResult call);
The implementation on the client and the
Contract Features Service and Operation Contracts One-Way, Request-Reply, Duplex, Faults Sessions, First/Last Operation Names,Namespaces
Message and Data Contracts Message Schema
Security
ProtectionLevel on Service, Operation, & Message contracts
Fine-grained Control
Action, Direction, Headers, Body, Wrapped/Bare, RPC/Doc, Literal/Encoded
Bindings & Binding Elements Binding
HTTP
Transport
Text
Security
TX
Reliability
Encoders
Protocol
TCP
HTTP
Text
Security
Reliability
MSMQ
IPC
Binary
TX
.NET
Custom
Custom
Custom
Standard Bindings Binding
Interop
BasicHttpBinding
BP 1.1
Securit Sessio TX y n N, T N N
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
T
N
N
T, M, X
N
N, Yes No
T
N
N, Yes n/a
Peer
NetMsmqBinding .NET MsmqIntegrationBindin MSMQ g
Duple x n/a
Yes
N = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions
Choosing Bindings WCF ASMX/WSE3 WCF Other Platform WCF
Any Protocol Any Any Binding Binding
WCF
WS-* Protocols Http/WS
WCF
Binding
Http/WS WS-* Protocols Binding
WS-* Protocols Http/WS Binding
Http/WS WS-* Protocols Binding
MSMQ Protocol
MSMQ WCF
MSMQ Binding
MSMQ Protocol
MSMQ Binding
ASMX/WSE3 WCF Other Platform WCF MSMQ
Binding Elements’ Features Transport selection TCP, HTTP, Named Pipes, P2P, MSMQ, Custom Transport level security, Streaming
Encoding
Text, Binary, 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
Hosting: Self-Host class HelloHost { static void Main(string[] args) { ServiceHost host = new ServiceHost(typeof(HelloService)); host.Open(); Console.ReadLine(); host.Close(); } } <service name="HelloService">
…
Hosting: Self-Host Pros Complete control Unlimited in binding/behavior choices Client scenarios: UI applications
Cons No hosting management features
Hosting: Windows Service
public class WindowsService : ServiceBase { ServiceHost host; protected override void OnStart(string[] args) { host = new ServiceHost(typeof(HelloService)); host.Open(); } protected override void OnStop() { host.Close(); } } [RunInstaller(true)] public class WindowsServiceInstaller : Installer { public WindowsServiceInstaller() { ServiceProcessInstaller spi = new ServiceProcessInstaller(); ServiceInstaller si = new ServiceInstaller(); Installers.Add(spi); Installers.Add(si); } }
Hosting: Windows Service Pros Auto Start/Stop/Restart SCM management tool Can run under user or machine accounts
Cons No message-based activation
Hosting: IIS6 & IIS7/WAS http://localhost/HelloService/HelloService.svc <%@ Service language="C#" class="HelloService" %> using System; using System.ServiceModel; public class HelloService : IHelloService { … }
Hosting: IIS6 Pros Auto Compilation Message-based Activation App Pools/Process Recycling IIS management ASP.Net Compatibility Mode option
Cons Only http transport bindings supported
Hosting: IIS7/WAS Pros Activation decoupled from IIS Adds support for Named Pipes, TCP, and MSMQ New IIS7 Management tool
Cons Works on Vista, but “Longhorn” Server not here yet
Behaviors Client C
B
Be
Client Behaviors
A
A
B
C
A
B
C
A
B
C
Service
Be
Service Behaviors
Example: Security Client C
B
A
Be
A
B
C
A
B
C
A
B
C
Service
Be
Bindings Insert Claims in Messages Behaviors Implement Security Gates
Example: Transactions Client C
B
A
Be
A
B
C
A
B
C
A
B
C
Service
Be
Bindings Flow Transactions Behaviors AutoEnlist and AutoComplete
Behavior Features Operation timeouts (close, open, idle) Concurrency, Instancing, ThreadBinding Throttling Faults, Exceptions Impersonation, Authorization, Auditing AutoEnlist, AutoComplete, Timeout, Isolation Serialization, MustUnderstand Metadata
Service Instancing Instancing controls service instance lifetime [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] Instance options Per Call Per Session Shared Instance Singleton
Instancing: Per Call Instance created before each call, disposed after each call Best for individualized requests without lots of resource management Server must manage own state correlation
Instancing: Per Session Best for session-based contracts. Instance for each established session. Customize instance mangement with OperationBehavior[ReleaseInstanceMo de=] ReleaseInstanceModes: None, BeforeCall, AfterCall, BeforeAndAfterCall OperationContext.Current.InstanceCont ext.ReleaseServiceInstance()
Instancing: Shared Instance
Augments PerSession with sharability Client Creates session with new Service Instance Obtains EndpointAddress of Service Instance – proxy.InnerChannel.ResolveInstance() Shares EndpointAddress with other clients Others establish own sessions with instance
Service Instance lives until all clients
Instancing: Singleton Single instance of Service Service should synchronize state as clients will access on multiple threads (same with Shared Instance). Singleton service can be instantiated and passed to ServiceHost constructor.
Throttling By default, throttling disabled. When enabled, extra requests queued. MaxConcurrentCalls MaxConnections MaxInstances Values interpreted based on Instance mode.
Security Settings Contract: ProtectionLevel: at Service, Operation and Message Contract levels None, Sign, EncryptAndSign. Binding: SecurityMode: None, Transport, Message, Both, TransportWithMessageCredential, TransportCredentialOnly ClientCredentialType: None, Windows, UserName, Certificate, IssuedToken NegotiateServiceCredential: turn-off for one-shot messages EstablishSecurityContext: provides security session AlgorithmSuite: allows control of algorithm suite
Security Credentials I ClientCredentialType: Windows – Intranet Use Windows Domain, supports Kerberos, NTLM, SPNego Well integrated into Windows application model. UserName - Internet Can be logged in to Windows account. Needs channel encryption (Server certificate, transport security) for safe transmission. Service must write username/password management or use ASP.Net Membership provider. Certificate – B2B Service can map client certificates to windows accounts. Service can be configured to customize trust policies on client certificates. IssuedToken - Federation Requires WsFederationBinding Client is issued token, for example SAML token, with custom claims. Service then authenticates token and authorizes
Security Credentials II Behaviors: <serviceCredentials>,
Credentials: Client & Service credentials configuration
Provide app’s credentials Service can configure client certificate trust, manage username/passwords
Addresses: Identity: Specify Server’s Kerberos identity, X.509 certificate identity.
For cases where host name is not enough information. Allows passing endpoint addresses to other services that can be securely communicated with. Generated for client through svcutil proxy generation.
Security Authorization Behaviors: <serviceAuthorization> WCF Claims-Based Authorization
OperationContext.Current.ServiceSecurityContext Provides PrimaryIdentity, WindowsIdentity, AuthorizationContext, and AuthorizationPolicies Implement IAuthorizationPolicy for auto-evaluation
Role-based security
principalPermissionMode: Windows*, UseAspNetRoles, Custom *Certificates and user names that to Windows will produce Windows identity and it’s groups as roles [PrincipalPermission(SecurityAction.Demand, Role = “Owners")] public void Manage(…); System.Threading.Thread.CurrentPrincipal.IsInRole()
Security Impersonation have identity of caller on thread: I Services System.Threading.Thread.CurrentPrincipal Some Services wish to set caller’s identity as current user of thread, i.e. Impersonate [OperationBehavior(Impersonation = ImpersonationOption.NotAllowed, Allowed or Required)] public void ActAsCaller(…); Client must choose allowed impersonation level in ClientCredentials
Security Impersonation AllowedImpersonationLevels IIAllowedImpersonationLevels None & Anonymous: User appears anonymous
Identification: Service can impersonate caller but can’t pass any ACL checks as caller Impersonation*: Service can impersonate caller and can pass any ACL checks on box. Delegation**: Service can impersonate caller and make network requests as caller to a service that will impersonate caller and pass ACL checks. *To impersonate, your account must have SE_Impersonate privilege, given to NetworkService. **To enable Delegation or Constrained Delegation in a Windows Domain, the caller’s account and delegating service’s account need to be given proper permissions by the Domain Administrators.
Features Summary Address
Binding
http://...
HTTP Transport
net.p2p://...
Peer Transport
net.tcp://...
net.pipe://...
net.msmq://...
xxx://...
WS-Security Protocol
WS-RM Protocol
NamedPipe Transport
WS-AT Protocol
Custom Transport
Externally visible, perendpoint
Request/ Response
Behavior Instancing Behavior
Concurrency Behavior
Throttling Behavior
TCP Transport
MSMQ Transport
Contract
Metadata Behavior One-Way
Error Behavior
Transaction Behavior
Custom Behavior
Security Behavior
Duplex Channel Duplex
Custom Protocol
Opaque, per-service, endpoint, or op
WCF “Architecture” Summary Application
Messaging Services Queuing
Routing
Eventing Discovery
Service Model Instance Context Service Type Declarative Transacted Manager Manager Methods Integration Behaviors Methods
Channels Reliability
Transport Channels (IPC, HTTP, TCP…)
Message Encoder
Security
Hosting Environments WAS
IIS
.exe
Windows Service
DllHost
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