Anda di halaman 1dari 48

Windows

Communication
Foundation

Giovanni Della-Libera
Principal Software Design
Engineer
Connected Systems Division
Microsoft Corporation
giodl@microsoft.com
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.
Foundation
The unified programming model for
rapidly building service-oriented
rapidly building service-oriented
applications on the Windows platform
• Unifies today’s distributed technology
Unification stacks
• Appropriate for use on-machine, cross-
machine, and across Internet
• Codifies best practices for building
Service distributed applications
Orientation • Maximizes productivity

• Interoperates with applications running on


Integration other platforms
• Integrates with our own distributed stacks
From Objects to
Services
In Search of Better Application Building
Blocks Object-Oriented
Encapsulation
1980s Polymorphism
Subclassing

Component-Oriented
Dynamic Loading
1990s Interface-based
Runtime Metadata

Service-Oriented
Message-based
Schema+Contract
2000s Binding via Policy
Service Orientation
Key Concepts
Applications
Operational
Requirements State
composed of
enforce manage

Policies governed by Services

have bound by exchange

Message Exchange Messages


Pattern
Contracts
describe is a set of

made of Schemas define structure of


Endpoints

Client Service
Endpoint

Endpoint Endpoint

Endpoint
Address, Binding,
Contract
Client Service
A B C

C B A A B C

A B C

Address Binding Contract


Where? How? What?
Creating Endpoints

Client Service
A B C

C B A A B C

ChannelFactory A B C

ServiceHost
Service Configuration
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="HelloService">
<endpoint
address="http://localhost/HelloService"
binding="basicHttpBinding"
contract="IHello" />
</service>
</services>
</system.serviceModel>
</configuration>
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
[ServiceContract]
wsdl:portType public interface MyContract {
[OperationContract]
wsdl:operation MyReply MyOp(MyRequest request);

[OperationContract]
void MyOp2(MyRequest2 request);
}
Describes the
service
operation
Operations Types
Operations w/ void Buy( ItemInfo info,
Parameters
int amount );
(shorthand for TM)

Typed void Buy( MyRequest msg );


Message

Untyped
(“Universal”) void Buy( Message m );
Describing the Message
Format
wsdl:message [MessageContract]
public class MyRequest {
[MessageHeader] public int Amount;
wsdl:part
[MessageBody] public ItemInfo Info;
}

[DataContract]
xsd:element public class ItemInfo {
[DataMember] public int ID;
[DataMember] public double Cost;
[DataMember] public string Name;
}
Message Exchange
Patterns
Request/Repl [OperationContract]
string Echo(string text);
y
[OperationContract(IsOneWay = true)]
One Way void LogIt(DateTime stamp, string str);

[ServiceContract(CallbackContract=typeof(IChat)]
public interface IChat {
Duplex [OperationContract(IsOneWay = true)]
void Chat(string text);
}

[ServiceContract(SessionMode=
Session SessionMode.Required)]
public interface IConnection { … }
Controlling Message
Dispatch
SOAP messages have Actions
<wsa:Action>http://tempUri.org/IFoo/Bar</wsa:Action>

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
Async
On the wire everything is asynchronous
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 Text Security Reliability TX

Transport Encoders Protocol


TCP HTTP Text Security Reliability

MSMQ IPC Binary TX .NET

Custom
Custom Custom
Standard Bindings
Securit Sessio Duple
Binding Interop TX
y n x
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
MsmqIntegrationBindin
MSMQ T N N, Yes n/a
g
N = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions
Choosing Bindings
WCF Any Any Protocol Any WCF
Binding Binding

WS-* Protocols Http/WS


ASMX/WSE3 WCF
Binding

Http/WS WS-* Protocols


WCF Binding
ASMX/WSE3

Other Platform WS-* Protocols Http/WS WCF


Binding

Http/WS WS-* Protocols


WCF Binding
Other Platform

MSMQ MSMQ MSMQ WCF


Protocol Binding
MSMQ MSMQ
WCF Protocol MSMQ
Binding
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">
  <host>
    <baseAddresses>
      <add baseAddress="http://localhost:8000"/>
    </baseAddresses>
  </host>

</service>
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 Service
A B C

C B A A B C

A B C
Be
Be

Client Service
Behaviors Behaviors
Example: Security

Client Service
A B C

C B A A B C

Be A B C
Be
Bindings Insert
Claims in
Messages

Behaviors
Implement
Security Gates
Example: Transactions

Client Service
A B C

C B A A B C

Be A B C
Be

Bindings Flow
Transactions

Behaviors
AutoEnlist and
AutoComplete
Behavior Features
Operation timeouts (close, open, idle)
Concurrency, Instancing, Thread-
Binding
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>,<clientCredentials>
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
I Services have identity of caller on thread:
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
IIAllowedImpersonationLevels
AllowedImpersonationLevels
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 Contract Behavior
HTTP WS-Security Request/ Instancing Concurrency
http://...
Transport Protocol Response Behavior Behavior

Peer
net.p2p://...
Transport
Throttling
Behavior
TCP WS-RM
net.tcp://... Protocol
Transport
Metadata
Behavior
net.pipe://...
NamedPipe WS-AT
Transport Protocol One-Way
Error Transaction
Behavior Behavior
net.msmq://...
MSMQ Duplex
Transport Channel
Custom Security
Duplex Behavior Behavior
xxx://...
Custom Custom
Transport Protocol

Externally visible, per- Opaque, per-service, endpoint, or


endpoint 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
Transport Channels Message
Reliability (IPC, HTTP, TCP…) Encoder Security

Hosting Environments
WAS IIS .exe Windows DllHost
Service
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

Anda mungkin juga menyukai