Vous êtes sur la page 1sur 62

An Introduction to

Windows Communication
Foundation

Mikael Deurell
Senior Consultant
Microsoft
mikael.deurell@microsoft.com
http://blogs.msdn.com/deurell
Agenda
WCF Basics
What is WCF
WCF’s ABC - Address, Binding & Contract
Service Hosting and Client Programming
Demo
Advanced WCF
Reliability
Instance Management and Session
Message Exchange Patterns
Transactions
Security
Microsoft’s Integration Technologies
Resources
Q&A
A brief introduction to the technology
What is the Windows Communication
Foundation?
A Software Factory Template for
Communication
Software Factory Template Windows Communication
Foundation
Domain Specific Language Service Model
Address + Binding + Contract
& Behaviors
Fine-Grained Class Library Channel Layer

Protocols

Run-Time Services and Proxies


<service> Address +
<endpoint name=“MyService”
address=“MyAddress” Binding +
binding=“netTcpBinding” Contract =
contract=“IMyInterface” />
[ServiceContract]
Endpoint
public interface IMyInterface Service
{
[FaultContract(typeof(MyFault)] Contract
[OperationContract]
Definition
public void MyMethod(MyDataContract);
}

[DataContract] Data
public class MyDataContract Contract
{ [DataMember]
public string MyField; Definition
}

[ServiceBehavior(InstanceContextMode=Single]
public class MyService: IMyInterface
{ Service Type
public void MyMethod(MyDataContract){…}
}
Windows Communication Foundation “Crown
Jewels”

Service Model Programming Model

Pluggable Software Factory Architecture

Claims-based Authorization

Management Facilities
Windows Communication Foundation
Architecture

User Code User Code

Typed Proxy Dispatcher

Protocol #1 Protocol #1
B B
i i
Protocol #n n n Protocol #n
d d
i i
Encoder n n Encoder
g g
Transport Transport

Message
Putting the pieces
together…
Windows Communication Foundation (WCF, code
named Indigo) is a programming platform and runtime
system for building, configuring and deploying
network-distributed services.
It is an unified programming model provided in .Net
Framework 3.0 (WinFX).

ASMX .NET
Remotin
Interop g
Extensibility
with other Location
platforms transparency

WS-* Message-
Protocol Attribute- Oriented
Support Based Programming
Programming
WSE System.Messagi
Enterprise ng
Services
Agenda
WCF Basics
What is WCF
WCF’s ABC - Address, Binding &
Contract
Service Hosting and Client Programming
Demo
Advanced WCF
Reliability
Instance Management and Session
Message Exchange Patterns
Transactions
Security
Demo
Microsoft’s Integration Technologies
Resources
Address, Binding &
Contract
A Service Endpoint has an Address, a Binding, and a
Contract (ABC).
An Address is a network address indicates where the
service is located.
A Binding specifies how a client can communicate with the
endpoint including transport protocol, encoding, and
security requirements.
A Contract identifies what operations are available to the
clients.
Client A B C Service
C B A A B C

A B C

Address Binding Contract


Where? How? What?

Endpoint
Service Addresses
Every service is associated with a unique address.
Base address format
[transport]://[host name][:optional
port]/[optional path]
Base address describes where it provides the metadata
for the service (WSDL).
Endpoint address format
[base address]/[optional path]
Endpoint address is where the service is actually
listening. This can be an absolute URI or relative to the
base address.
Build-in transports: HTTP/S, TCP, P2P, IPC and MSMQ
Examples
http://localhost:8001/MyService/BP
http://localhost:8001/MyService/WS
net.tcp://localhost:8002/MyService
net.pipe://localhost/MyPipe
net.msmq://localhost/private/MyQueue
Service Bindings
 It specifies the communication details required to connect to the
endpoint.

Transport

Encoding

Interop

Security

Session

Transaction

Duplex

Streaming
Binding Name
BasicHttpBinding HTTP/S Text.MTOM BP 1.1 T X
WsHttpBinding HTTP/S Text.MTOM WS T|S X X X
WsDualHttpBinding HTTP/S Text.MTOM WS T|S X X X X
NetTcpBinding TCP Binary .NET T|S X X X X
NetNamedPipesBinding IPC Binary .NET T|S X X X X
NetMsmqBinding MSMQ Binary .NET T|S X
NetPeerTcpBinding P2P Binary .NET T|S X
MsmqIntegrationBinding MSMQ Binary MSMQ T X
T = Transport Security | S = WS-Security
Text.MTOM (Message Transmission Optimization Mechanism) is a W3C standard
to balance between efficiency and interoperability. The MTOM encoding
transmits most XML in textual form, but optimizes large blocks of binary data
by transmitting them as-is, without conversion to text.
Service Contracts
Contract defines the operations of a service
[ServiceContract]
public interface IMyContract
{
[OperationContract]
string Hello(string name);
}

Implementing the service


public class MyService : IMyContract
{
public string Hello(string name)
{
string greeting = "Hello " + name;
Console.WriteLine(greeting);
return greeting;
}
}
Agenda
WCF Basics
What is WCF
WCF’s ABC - Address, Binding & Contract
Service Hosting and Client
Programming
Demo
Advanced WCF
Reliability
Instance Management and Session
Message Exchange Patterns
Transactions
Security
Demo
Microsoft’s Integration Technologies
Resources
Service Hosting
IIS 6 (ASPNET_WP.EXE / W3wp.exe)
Activation on demand upon client request.
Only supports HTTP/S transport.
Self Hosting
Can be any managed application, i.e. Console
or WinForms application.
Low-level but flexible.
Windows Activation Service (WAS)
Supports all transports.
Will ship with IIS 7 on Vista and Longhorn
Server.
Managed Windows Services (NT Services)
Self Hosting
Create a service host
Open the host to allow calls in
Close the host to gracefully exit
Calls in progress complete.
Host refuse any further calls even if host process is still
running.
public static void Main ()
{
Uri baseAddress = new Uri ("http://localhost:8000");
using (ServiceHost serviceHost =
new ServiceHost (typeof(MyService),
baseAddress))
{
serviceHost.Open ();
// The service can now be accessed.
Console.WriteLine ("Press <ENTER> to terminate
service.");
Console.ReadLine ();
}
Service Configuration
Application hosting
App.Config
<system.serviceModel>
<services>
<service name = "MyNamespace.MyService" >
<endpoint
address = "http://localhost:8000/MyService"
binding = "wsHttpBinding"
contract = "MyNamespace.IMyContract">
</endpoint>
</service>
</services>
</system.serviceModel>
Service Configuration
(cont.)
IIS/WAS hosting
Web.Config
<system.serviceModel>
<services>
<service name = "MyNamespace.MyService" >
<endpoint
address = " "
binding = "wsHttpBinding"
contract = "MyNamespace.IMyContract">
</endpoint>
</service>
</services>
</system.serviceModel>
Service file (.svc)
<%@ServiceHost language=c# Debug= "false"
Service=“MyNamespace.MyService" %>
Service address
http://<Web Server>/<Service Virtual Directory>/<Service
File>
Client Programming 1
Client uses a proxy to consume the service
The proxy
Is CLR interface and class representing the service.
Provides the same operations as service.
Has additional methods for managing the proxy and the
connection.
Generate the proxy
SvcUtil.exe <Base Address> [/out:<file>]
[/config:<file>]
When hosted in IIS/WAS
SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs
When self-hosting
SvcUtil http://localhost:8000/MyService/ /out:Proxy.cs
SvcUtil net.tcp://localhost:8001/ /out:Proxy.cs
SvcUtil net.pipe://localhost/MyPipe/ /out:Proxy.cs
HTTP transport
Add Service Reference to the project in VS 2005
Client Programming 2
Client Configuration
Application: App.Config

<system.serviceModel>
<client>
<endpoint name="MyEndpoint"
address="http://localhost:8000/MyService"
binding="wsHttpBinding"
contract="MyNamespace.IMyContract" />
</client>
</system.serviceModel>
Client Programming 3
Client needs to instantiate proxy
object
Provide the constructor with endpoint
Endpoint section name from config file
Use service methods
Close proxy instance
using (MyContractProxy proxy = new MyContractProxy
("MyEndpoint") )
{
proxy.MyMethod ();
}
Client Programming 4
No Proxy Client
Work directly with channel
ChannelFactory<IMyContract> factory =
new ChannelFactory<IMyContract> ("MyEndpoint");
IMyContract channel = factory.CreateChannel();
channel.MyMethod ();
factory.Close ();

 Need to know the contract interface


upfront
Demo
Hello World
Multiple endpoints
IIS Hosting
Agenda
WCF Basics
What is WCF
WCF’s ABC - Address, Binding & Contract
Service Hosting and Client Programming
Demo
Advanced WCF
Reliability
Instance Management and Session
Message Exchange Patterns
Transactions
Security
Demo
Microsoft’s Integration Technologies
Resources
Q&A
Reliability
Provides reliable message transfer
Messages are delivered exactly once, in
the same order as they are sent
A direct communication model (“TCP at
the SOAP level”)
Resilient to
Transport disconnections
SOAP or transport intermediary failures
Ordered messages
All bindings that support reliability
support ordered messages
Default is enabled
Reliability and Bindings
Reliability supported but disabled by
default
WS binding
TCP binding
Reliability always enabled
WS dual binding
Reliability not supported
Basic binding
Peer TCP binding
Reliable without using WCF reliability
MSMQ/MSMQ integration binding
Reliability and Bindings
(Cont.)
Binding Name Supports
Reliability
Default
Reliability
Supports
Order
Default
Order
BasicHttpBinding No N/A No N/A

WsHttpBinding Yes Off Yes On

WsDualHttpBinding Yes On Yes On

NetTcpBinding Yes Off Yes On

NetNamedPipesBinding Yes On Yes On

NetMsmqBinding No N/A No N/A

NetPeerTcpBinding No N/A No N/A

MsmqIntegrationBinding Yes On Yes On


Reliability Configuration
<system.serviceModel>
<services>
<service name = "MyNamespace.MyService" >
<endpoint
address = "http://localhost:8000/MyService"
binding = "wsHttpBinding“
bindingConfiguration = "ReliableWS"
contract = "MyNamespace.IMyContract">
</endpoint>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name = “ReliableWS" >
<reliableSession enable = "true" ordered =
"true"
inactivityTimeout =
“00:10:00" />
</binding>
</wsHttpBinding >
Agenda
WCF Basics
What is WCF
WCF’s ABC - Address, Binding & Contract
Service Hosting and Client Programming
Demo
Advanced WCF
Reliability
Instance Management and Session
Message Exchange Patterns
Transactions
Security
Demo
Microsoft’s Integration Technologies
Resources
Q&A
Service Behaviors
Instance management
Transactions
Security
Concurrency
The ConcurrencyMode property controls
the per-instance threading behavior of a
service.
Error handling
Exceptions not propagated to client by
default.
Throttling
Limits the number of clients, service
Instance Management
Modes of Service Instances
Per-call (default)
A new service instance is created and
destroyed for every call
Per-session
One service instance per client
Clients cannot share instance with other
clients
Sharable
One service instance per client
Client can share service instance with other
client.
Sessions
WCF can maintain a private session between a
client and a particular service instance.
The client session has one service instance per
proxy.
Can maintain the state in memory between calls.
You can enable session at contract level
Per-session and sharable services require
session. (Session = true)]
[ServiceContract
public interface IMyContract
{…}

[ServiceBehavior(InstanceContextMode =
InstanceContextMode.PerSession)]
public class MyService : IMyContract
{…}
Sharable Instances
By default, InstanceContectMode.Sharable
behaves just like
InstanceContectMode.PerSession.
To use the sharable instance, the client
needs to pass a logical instance reference to
another client by:
Duplicating a proxy if the clients are in the same
app domain.
Passing instance reference from one client to
another over WCF.
Demo
Per-session instance
Singleton instance
Agenda
WCF Basics
What is WCF
WCF’s ABC - Address, Binding & Contract
Service Hosting and Client Programming
Demo
Advanced WCF
Reliability
Instance Management and Session
Message Exchange Patterns
Transactions
Security
Demo
Microsoft’s Integration Technologies
Resources
Q&A
Message Exchange
Patterns
Request/Reply (Default)
A client calls a method (the request) and
waits until the service returns a value
(the reply).
One-Way
Once a method is called, no response is
required.
Duplex
Both the service and the client can send
messages to each other independently.
One-Way Operations
Client does want to guarantee
invocation
Does not care about results, errors,
timing and invocation order.
[ServiceContract (Namespace = "MyNamespace")]
public interface IMyContract
{
[OperationContract(IsOneWay = true)]
void MyMethod(…);
}
Duplex Operations
Allowing service to call back to
clients
Client becomes the service
Service becomes the client
Requires bi-directional-able
communication binding
TCP
Named pipes
WS dual
Can implement Publish/Subscribe
Agenda
WCF Basics
What is WCF
WCF’s ABC - Address, Binding & Contract
Service Hosting and Client Programming
Demo
Advanced WCF
Reliability
Instance Management and Session
Message Exchange Patterns
Transactions
Security
Demo
Microsoft’s Integration Technologies
Resources
Q&A
Transactions
WCF provides a rich set of features that
enable to create distributed transactions in
Web service application.
WCF transactions support OLETX and WS-
AtomicTransaction (WS-AT) protocols
OLETX for Microsoft platform and WS-AT
for interop
Transaction-aware bindings
TCP
Named Pipes
WS
WS Federation
WS Dual
Transaction Flow
Client Transaction
Service must use client transaction
Client/Service Transaction
Service joins client transaction if client
flows one.
Service is root of new transaction if no
transaction was propagated.
Service Transaction
Service performs transactional work
outside scope of client transaction.
Client Transaction 1
TransactionFlow attribute specifies if
the client transaction can flow to
service.
Specify a transaction flow option on
the contract methods that should
[ServiceContract (Namespace = "MyNamespace")]
flow a transaction.
public interface IMyContract
{
[OperationContract]

[TransactionFlow(TransactionFlowOption.Man
datory)]
void MyMethod(…);
}
Client Transaction 2
Specify a transactional behavioral
attribute on the methods, using
TransactionScopeRequired property.
public class MyService : IMyContract
{
[OperationBehavior(TransactionScopeRequired =
true)]
public string MyMethod(…)
{

}
}
Client Transaction 3
Transaction flow is enabled by using
transactionFlow attribute in config file
on both service and client.
<system.serviceModel>
……
<bindings>
<wsHttpBinding>
<binding name = "Binding1"
transactionFlow = "true"
/>
</wsHttpBinding >
</bindings>
</system.serviceModel>
Client Transaction 4
Create a TransactionScope.
Defines a region within which a
transaction is active
Call the service methods on the
client.
Commit
using the transaction.
(TransactionScope tx =
new TransactionScope
(TransactionScopeOption.RequiresNew))
{
// Do something
proxy.MyMethod();
tx.Complete();
}
Transaction Summary
Client TransactionFlowOption TransactionScopeRequired Transaction
Transaction
Propagated
No Allowed False None
No Allowed True Service
No NotAllowed False None
No NotAllowed True Service
Yes Allowed False None
Yes Allowed True Client/Service
Yes Mandatory False None
Yes Mandatory True Client
Agenda
WCF Basics
What is WCF
WCF’s ABC - Address, Binding & Contract
Service Hosting and Client Programming
Demo
Advanced WCF
Reliability
Instance Management and Session
Message Exchange Patterns
Transactions
Security
Demo
Microsoft’s Integration Technologies
Resources
Q&A
Security
Transfer Security
Integrity
Confidentiality
Authentication
Access Control
Authorization
Auditing
Log security related events to the event
log
Security (cont.)

Contract can specify protection


level
Binding specifies
Security mode (Transport / Message)
Algorithms
Types of credentials
...
Behavior specifies
Client credentials
Service credentials
Security Protection Level
Service and operation can specify
protection level
None
Sign
EncryptAndSign

[ServiceContract (ProtectionLevel = ProtectionLevel.Sign)]


public interface IMyContract
{
[OperationContract(ProtectionLevel =
ProtectionLevel.EncryptAndSign)]
void MyMethod(…);
}
Transfer Security Modes
None: Anonymous. No security is
provided.
Transport: Secured using Transport layer
security (SSL for example). Secure point-
to-point.
Message: SOAP Messages are secured
using the WS-Security standards. Secure
end-to-end.
Mixed (Transport With Message
Credential): Uses transport security for
confidentially, integrity and server
authentication. It will use message
security for client authentication. (i.e.
Transfer Security Modes
Binding Name None Transport Message Mixed Both

BasicHttpBinding Yes Yes Yes Yes No

WsHttpBinding Yes Yes Yes Yes No

WsDualHttpBinding Yes No Yes No No

NetTcpBinding Yes Yes Yes Yes No

NetNamedPipesBinding Yes Yes No No No

NetPeerTcpBinding Yes Yes Yes Yes No

NetMsmqBinding Yes Yes Yes No Yes

MsmqIntegrationBinding Yes Yes No No No

Default: Bold
Client Authentication
Types
Transport Mode Message Mode
None None
Basic Windows
Digest Username
NTLM Certificate
Windows WCS (InfoCard)
Certificate
Credential Type Options by Binding
Transport Security Mode
Binding ClientCredentialType Options Service Credential
BasicHttpBinding None, Basic, Digest, Ntlm, Windows, None (http) or Certificate (https)
Certificate
WSHttpBinding None, Basic, Digest, Ntlm, Windows, None (http) or Certificate (https)
Certificate
WSDualHttpBinding N/A N/A
NetTcpBinding None, Windows, Certificate Windows, Certificate
NetNamedPipeBinding Windows Windows
NetMsmqBinding None, Windows, Certificate None
MsmqIntegrationBinding None, Certificate None
Message Security
Binding Mode ClientCredentialType Options Service Credential
BasicHttpBinding None, Certificate, UserName, WCS Certificate
WSHttpBinding None, Certificate, UserName, Windows, WCS Windows, Certificate
WSDualHttpBinding None, Certificate, UserName, Windows Windows, Certificate
NetTcpBinding None, Certificate, UserName, Windows, WCS Windows, Certificate
NetNamedPipeBinding NA NA
NetMsmqBinding None, Certificate, UserName, Windows, WCS None
MsmqIntegrationBinding NA NA

Default Security
Security Configuration
Configured in bindings on service and
client
In code or config file
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name = "SecurityOptions" >
<security mode = "Message" >
<message clientCredentialType =
"Windows" />
</security >
</binding>
</wsHttpBinding >
</bindings>
</system.serviceModel>
Authorization
Once a user has been authenticated, the
system can determine whether that user is
allowed to perform the action they are
attempting.
When client credentials are used, the
PrincipalPermission attribute is applied on
methods to declare required role
memberships.
ServiceSecurityContext will give you the
client Identity.
Role-Based Security Configuration

Set authentication mode


None
Use Windows Groups
Use ASP.Net Roles - refer to ASP.NET
2.0 MembershipProvider
Custom >
<system.serviceModel
<services>
<service name = "MyNamespace.MyService" behaviorConfiguration =
"WindowsGroup">

</service>
</services>
<behaviors>
<behavior name = “WindowsGroup" >
<serviceAuthorization principalPermissionMode =
"UseWindowsGroups" />
</behavior>
</behaviors >
Role-Based Security Configuration
(cont.)
Declare required role memberships
public class MyService : IMyContract
{
[PrincipalPermission(SecurityAction.Demand,
Role = @"<domain>\<group
name>")]
public string MyMethod(…)
{

}
}
Agenda
WCF Basics
What is WCF
WCF’s ABC - Address, Binding & Contract
Service Hosting and Client Programming
Demo
Advanced WCF
Reliability
Instance Management and Session
Message Exchange Patterns
Transactions
Security
Demo
Microsoft’s Integration Technologies
Resources
Q&A
Microsoft’s Integration
Technologies
Windows Windows
Communication
Workflow
Foundation Foundation

BizTalk Server

SQL-to-SQL
Brokered
Unbrokered communication
B2Bservice-to-service
integration using optimized
with orchestration,
communication binary protocol
transformation,
using WS-* adapters
protocols
WCF and BizTalk Server
BizTalk and WCF are complementary
technologies.
WCF provides a unified framework for
building secure, reliable and transacted
Web services for simple point-to-point
integration .
BizTalk provides business process
orchestration, message transformation,
business activity monitoring, and more
through designers and visual tools.
BizTalk will provide a WCF adapter that
enables WCF services to be incorporated
into business process orchestration.
© 2006 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other
countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing
market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this
presentation.
MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Vous aimerez peut-être aussi