Académique Documents
Professionnel Documents
Culture Documents
Framework
Technical Drilldown
Jeff Brand
.NET Architect
Microsoft – Minneapolis
jbrand@microsoft.com
http://www.slickthought.net
Agenda
Intro
The Basics
Understanding Bindings
Reliable Messaging
Security
What is .NET 3.0?
Formerly WinFX
New managed code programming model for
Windows
Combines the power of the .NET Framework 2.0
with new technologies for building applications
Visually compelling user experiences
Seamless communication across technology boundaries
Ability to support a wide range of business processes
Runs on Windows XP SP2, Windows Server 2003
SP1 and Windows Vista
What?
What is the Windows Communication Foundation?
How?
How to use the Windows Communication Foundation?
Distributed Stacks Today
WCF
Message- Attribute-
WS-* Composability SOA
Oriented Based
Protocols Extensibility Interop
Programming Programming
The ABCs of Windows Communication
Foundation
A set of .NET 2.0 classes for building software services
[DataMember(Name=“TimeStamp”)]
private DateTime when
[DataMember(Name=“Date”)]
public DateTime When{ get{return this.when;}}
}
[DataContract(Name=“DealAnalysis”,Namespace=“WoodgroveBank”)]
public class Analysis
{
[DataMember]
public decimal Value;
[DataMember]
public decimal RiskFactor;
}
[ServiceContract(Name=“DealService”,Namespace=“WoodgroveBank”)]
public interface IDeal
{
[OperationContract(Name=“Analyze”)]
Analysis AnalyzeDeal(Deal dealToAnalyze);
[OperationContract(Name=“Execute”,IsOneWay=true)]
void ExecuteDeal(Deal dealToExecute)
}
Using the Windows
Communication
Foundation
Contracts
Structural c E
DataContract n
d
MessageContract
Program p
Behavioral o
ServiceContract i
OperationContract n
FaultContract t
Structural Contracts: Data
Contracts
Uncertainty/Polymorphism: c E
The other use for the KnownType attribute n
d
Program p
[DataContract] o
public class book{…}
i
[DataContract]
public class magazine{…} n
t
[DataContract]
[KnownType(typeof(Book))]
[KnownType(typeof(Magazine))]
public class PublishedItem
{
[DataMember]
object catalog;
[DataMember]
DateTime publicationDate;
}
Structural Contracts: Data
Contracts
Dealing with collections: c E
[MessageContract]
public class PurchaseOrderMessage
{
[MessageHeader]
public int Number;
[MessageBody(Order=1)]
public PurchaseOrder Order;
}
Using Windows Communication Foundation
(Service Programmer) Implement Contracts
[ServiceContract(Name=“DealService”,Namespace=“WoodgroveBank”)]
public interface IDeal
{ … }
[ServiceContract] i
public interface IOrderEntry
n
{
[OperationContract(IsOneWay=true)] t
void PlaceOrder(PurchaseOrder order);
}
[ServiceContract]
public interface IExtendedOrderEntry: IOrderEntry
{
[OperationContract]
PurchaseOrder GetOrder(String orderIdentifier);
}
Behavioral Contracts: Service
Contracts
Controlling how structural c E
contracts serialize n
d
Program p
[ServiceContract] o
[DataContractFormat(Style=OperationFormatStyle.Document)] //Or Rpc
public interface IOrderEntry i
{
n
…
} t
[ServiceContract]
[XmlSerializerFormat(Style=OperationFormatStyle.Document,
Use=OperationFormatUse.Literal)] //Or Encoded
public interface IOrderEntry
{
…
}
Behavioral Contracts: Service
Contracts
Duplex type c E
n
d
Program p
o
[ServiceContract(Session=true,CallbackContract=typeof(IOrderEntryCallback))]i
public interface IOrderEntry
n
{
[OperationContract(IsOneWay = true)] t
void PlaceOrder(PurchaseOrder order);
}
[ServiceContract]
public interface IOrderEntryCallback
{
[OperationContract(IsOneWay = true)]
void PlaceOrderCompleted(PurchaseOrderStatus orderStatus);
}
Behavioral Contracts: Operation
Contracts Use the OperationContractAttribute properties to
control the translation of the method signature into
WSDL:
E
The AsyncPattern property indicates that the c
operation is implemented asynchronously using a n
Begin/End method pair.
The IsOneWay property indicates that the operation d
only consists of a single input message. The
Program operation has no associated output message. p
The IsInitiating property specifies whether this
operation can be the initial operation in a session. o
The IsTerminating property specifies whether WCF
attempts to terminate the current session after the i
operation completes.
The Action property specifies the action that n
uniquely identifies this operation. WCF dispatches
request messages to methods based on their action. t
The ReplyAction property specifies the action of the
reply message for the operation.
[ServiceContract]
public interface IOrderEntry
{
[OperationContract(IsOneWay=true)]
void PlaceOrder(PurchaseOrder order);
}
Behavioral Contracts: Operation
Contracts
Action Property c E
use a wildcard action to provide a n
default message handler d
Program p
[ServiceContract]
o
public interface MyContract
{ i
[OperationContract(IsOneWay = true,
Action="urn:crud:insert")] n
void ProcessInsertMessage(Message message);
t
[OperationContract(IsOneWay = true,
Action="urn:crud:update")]
void ProcessUpdateMessage(Message message);
[OperationContract(IsOneWay = true,
Action="urn:crud:delete")]
void ProcessDeleteMessage(Message message);
Client view: c E
n
d
Program p
[DataContract(Name=”MyFault”)] o
public class ClientFault
{ i
[DataMember]
n
string Reason = null;
} t
…
try
{
PurchaseOrder order = Service.GetOrder(orderIdentifier);
}
catch (FaultException<ClientFault> clientFault)
{
Console.WriteLine(clientFault.Reason);
}
Using Windows Communication Foundation
(Service Programmer) Provide Host
[ServiceContract(Name=“DealService”,Namespace=“WoodgroveBank”)]
public interface IDeal
{ … }
(WPF or WinForms), t
(WAS)
Choosing the hosting
model depends on the
requirements of your
Service Implementation: Hosting
In standalone executables
E
c
n
Program
d
[ServiceContract]
public interface ILenderService {…} p
}
}
}
Service Implementation: Hosting
In an Managed Windows Service
Benefits:
Process lifetime controlled by O/S E
c
Built-in Service Control Manager n
Program d
[ServiceContract] p
public interface ILenderService {…}
o
internal class LenderService: ILenderService {…}
i
public partial class MyManagedService : ServiceBase
{ n
private ServiceHost host = null;
t
public MyNTService(){ InitializeComponent(); }
Service
protected override void OnStart(string[] args)
{
this.host = new ServiceHost(typeof(LenderService ));
service.Open();
}
//LenderService.svc
<%@Service Class="MyNamespace.LenderService" %>
<%@Assembly Name=“LenderServiceAssembly" %>
Bindings
Bindings = c E
Transports + n
Encoders + d
Deploy p
Protocols
o
i
b n
t
Service
Windows Communication Foundation
Architecture
Protocol B B Protocol
i i
n n
Encoding d d Encoding
i i
n n
Transport g g Transport
Message
Bindings: Transports
HTTP c E
TCP n
d
Deploy Named Pipes p
MSMQ o
i
b n
t
Service
Binding Options: The Standard Bindings
Interop.
Security
Session
s
Transaction
Duplex
BasicHttpBinding BP 1.1 T
WsHttpBinding WS T|S X X
WsDualHttpBinding WS T|S X X X
NetTcpBinding .NET T|S X X X
NetNamedPipesBinding .NET T|S X X X
NetMsmqBinding .NET T|S X X
MsmqIntegrationBinding .NET T
NetPeerTcpBinding .NET T|S X
T = Transport Security | S = WS-Security Message Security
Bindings: Encoding
Text c E
for interoperability n
d
Deploy Binary
p
for hi-speed WCF-to-WCF
o
MTOM i
Message Transmission b n
Optimization Protocol t
Service
Bindings
Binding options: c E
Select a standard binding n
Service
Using Windows Communication Foundation
(Service Administrator) Configure Binding
(Service Administrator) Configure Address
<configuration>
<system.serviceModel>
<services>
<service serviceType=“DealAnalyzer”>
<endpoint
address=“http://localhost:8080/Deals/AnalysisService”
binding=“wsHttpBinding”
contract=“IDeal”/>
</service>
</services>
</system.serviceModel>
</configuration>
Gotcha:
Initial characters of
binding names in
lowercase in config.
Binding Options: Modified Standard Bindings
<configuration>
<system.serviceModel>
<services>
<service serviceType=“DealAnalyzer”>
<endpoint
address=“http://localhost:8080/Deals/AnalysisService”
binding=“wsHttpBinding”
bindingConfiguration=“ReliableHttp”
contract=“IDeal”/>
</service>
</services>
<bindings>
<wsProfileBinding>
<binding configurationName=“ReliableHttp“>
<reliableSession Enabled=“true”/>
</binding>
</wsProfileBinding>
</bindings>
</system.serviceModel>
</configuration>
Binding Options: Custom Bindings
In code:
public static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(MathService),
“net.tcp://localhost/8080/MathService/”);
SecurityBindingElement s =
AsymmetricSecurityBindingElement.CreateKerberosBinding();
TextMessageEncodingBindingElement e =
new TextMessageEncodingBindingElement();
host.Open();
}
Binding Options: Custom Bindings
In configuration:
<?xml version=“1.0” encoding=“UTF-8” ?>
<configuration>
<system.serviceModel>
<services>
<service serviceType=“DealAnalyzer”>
<endpoint address=“http://localhost:8080/Deals/AnalysisService”
binding=“customBinding”
bindingConfiguration=“ReliableHttp”
contract=“IDeal”/>
</service>
</services>
<bindings>
<customBinding>
<binding configurationName=“ReliableHttp">
<reliableSession ordered="true” />
<security authenticationMode=“Kerberos” />
<textMessageEncoding />
<httpTransport maxMessageSize=“9223372036854775807" />
</binding>
</customBinding>
</bindings>
</system.serviceModel>
</configuration>
Security
WCF Security in a Nutshell
Confidentiality
Integrity
Authentication
Authorization
Auditing
Credential
Claims
Information about an entity
Used to control access to resources
Issuer
Certifies claims in the credential
Proof of possession
How an entity proves it provided the claims
Credential Examples
Alice
Username
MyDomain\Alice
Kerberos
Subject: CN=Alice
Issuer: SomeCA
ValidFrom: 2005-09-13
ValidUntil: 2005-09-16
Certificate
WCF Security Model
<basicHttpBinding>
<binding configurationName="Binding1">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</basicProfileBinding>
Message Security
<wsHttpBinding>
<binding configurationName="Binding1">
<security mode="Message">
<message clientCredentialType=“Windows"/>
</security>
</binding>
</wsHttpBinding>
Mixed Mode
<wsHttpBinding>
<binding configurationName="Binding1">
<security mode="TransportWithMessageCredential">
<message clientCredentialType=“Windows"/>
</security>
</binding>
</wsHttpBinding>
Username/Password
<behaviors>
<behavior configurationName="CalculatorServiceBehavior">
<serviceAuthorization
principalPermissionMode="UseWindowsGroups" />
</behavior>
</behaviors>
Federated Credentials
I’m Alice
Client Service
(SAML)
Trust Relationship
Credential Issuer
Federated Credentials
<bindings>
<customBinding>
<binding configurationName=”ReliabilityHTTP”>
<reliableSession/>
<httpTransport/>
</binding>
</customBinding>
</bindings>
Keeping It Consistent
[ServiceContract]
public interface IMyContract
{
[OperationContract]
[TransactionFlow(TransactionFlowOption.Required)]
bool Transfer1(Account from, Account to, decimal amount);
[OperationContract]
[TransactionFlow(TransactionFlowOption.NotAllowed)]
bool Transfer2(Account from, Account to, decimal amount);
}
Transactions: Interaction
Service Programmer
[BindingRequirements(
TransactionFlowRequirements=RequirementsMode.Require)]
[ServiceBehavior(
TransactionAutoCompleteOnSessionClose = true,
ReleaseServiceInstanceOnTransactionComplete = true)]
public class MyService: IMyContract
{
[OperationBehavior( TransactionScopeRequired = true,
TransactionAutoComplete = true)]
public bool Transfer1(Account from, Account to, decimal amount)
{ ... }
[OperationBehavior( TransactionScopeRequired = true,
TransactionAutoComplete = false)]
public bool Transfer2(Account from, Account to, decimal amount)
{ ...
OperationContext.Current.SetTransactionComplete();
}
}
Transactions: Usage
Client Programmer
TransactionScope transaction;
using (scope = new TransactionScope())
{
proxyForServiceOne.Transfer1(AccountOne, AccountTwo, amount);
proxyForServiceTwo.Transfer1(AccountThree,AccountFour,amount);
UpdateLocalCache(AccountOne, AccountTwo, amount);
scope.Complete();
}
Transactions: Control
Service Administrator
<bindings>
<wsHttpBinding>
<binding configurationName="SampleBinding“
transactionFlow=“true" />
</binding>
</wsHttpBinding>
</bindings>
How Queues Work
Caller Service
Message
Message
Queue Queue
Queues
Increase availability
Mask network or service unavailability
Support scale out
Multiple readers from a single queue
Provide load leveling
Handle average, not peak load
Are a building block for compensating transactions
Reliable, durable messaging to capture distributed
state changes
Need to compensate for errors
How Queues Work
Caller Service
Queue Queue
Message Message
Queue Endpoint
<endpoint
address ="net.msmq://MyServer/private$/MyQueue/”
binding="netMsmqBinding"
bindingConfiguration ="MyQueueBinding"
contract="IPurchaseOrder" />
Queues
Failure compensation
<endpoint
address ="net.msmq://MyServer/private/MyQueue;poison/”
bindingSectionName="netMsmqBinding"
bindingConfiguration ="MyQueueBinding"
contractType="Queue.IPurchaseOrder" />
Configuring Service Retries
<netMsmqBinding>
<binding configurationName="MyQueueBinding"
msmqAuthenticationMode="None“
msmqProtectionLevel="None"
maxRetries="2"
maxRetryCycles="3"
retryCycleDelay="0:0:10"
rejectAfterLastRetry="false" />
</netMsmqBinding>
To Poison
2 retries 10 Message
seconds Queue
WCF Manageability
V1
B1 CTP CTP B2 RCx
RTM
Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1
2005 2006 2007