WCF Technical Drilldown
-
Upload
api-3768963 -
Category
Documents
-
view
120 -
download
0
Transcript of WCF Technical Drilldown
Windows Communication Windows Communication Framework Framework
Technical DrilldownTechnical Drilldown
Windows Communication Windows Communication Framework Framework
Technical DrilldownTechnical Drilldown
Jeff BrandJeff Brand.NET Architect.NET ArchitectMicrosoft – MinneapolisMicrosoft – [email protected]@microsoft.comhttp://www.slickthought.nethttp://www.slickthought.net
AgendaAgenda
IntroIntro
The Basics The Basics
Understanding BindingsUnderstanding Bindings
Reliable MessagingReliable Messaging
SecuritySecurity
What is .NET 3.0?What is .NET 3.0?
Formerly WinFX Formerly WinFX New managed code programming model for New managed code programming model for Windows Windows Combines the power of the .NET Framework 2.0 Combines the power of the .NET Framework 2.0 with new technologies for building applicationswith new technologies for building applications
Visually compelling user experiencesSeamless communication across technology boundariesAbility to support a wide range of business processes
Runs on Windows XP SP2, Windows Server 2003 Runs on Windows XP SP2, Windows Server 2003 SP1 and Windows VistaSP1 and Windows Vista
Downloads, demos, presentations and more at Downloads, demos, presentations and more at http://www.netfx3.comhttp://www.netfx3.com
What is .NET 3.0?What is .NET 3.0?
Comprised of four main technologiesComprised of four main technologiesWindows Communication Foundation (“Indigo”)Windows Workflow (“WinOE”)Windows Presentation Foundation (“Avalon”)Windows CardSpace (“InfoSpace”)
Includes extensions to Visual Studio 2005 Includes extensions to Visual Studio 2005 to aid in application creationto aid in application creation
Looking at WCFLooking at WCF
Why?Why?What is the purpose of the Windows Communication Foundation?
What? What? What is the Windows Communication Foundation?
How?How?How to use the Windows Communication Foundation?
Each stack has different strengths, target scenariosEach stack has different strengths, target scenariosCustomers want to mix and match, composeCustomers want to mix and match, compose
Reliable servicesInteroperable transactions
ServicesServicesInteroperableInteroperable
ASP.NET InfrastructureASP.NET Infrastructure
ObjectsObjectsExtensibleExtensible
CLR InfrastructureCLR Infrastructure
ComponentsComponentsTransactionsTransactions
COM+ InfrastructureCOM+ Infrastructure
QueuingQueuingReliable MsgReliable Msg
MSMQ InfrastructureMSMQ Infrastructure
Distributed Stacks TodayDistributed Stacks Today
The Union of Today’s StacksThe Union of Today’s Stacks
WS-*WS-*ProtocolsProtocols
SOASOAInteropInterop
Attribute-Attribute-BasedBased
ProgrammingProgramming
Message-Message-OrientedOriented
ProgrammingProgramming
ComposabilityComposabilityExtensibilityExtensibility
WCFWCF
The ABCs of Windows Communication The ABCs of Windows Communication FoundationFoundation
A set of .NET 2.0 classes for building software servicesA set of .NET 2.0 classes for building software services
Deploy at some Deploy at some AddressAddressWithin any .NET assembly—console, windows, serviceWithin IIS 5.1 or 6 or IIS 7 Windows Activation ServiceEnjoy rich management interfaces out of the box:
perf counters, WMI, tracing and more
Connect to any topology by selecting & switching Connect to any topology by selecting & switching BindingsBindingsStandard bindings—eg. for max interop, or max perf. Custom bindings—for any transport, encoding and protocols
Define explicit interfaces as Define explicit interfaces as ContractsContractsBehavioral contracts—define what your software will doStructural contracts—define the formats of inputs and outputs
How to use the Windows Communication How to use the Windows Communication Foundation?Foundation?
Service: Service: • Define ContractsDefine Contracts• Implement Implement
ContractsContracts• Provide hostProvide host
• Configure BindingConfigure Binding• Configure AddressConfigure Address• MonitorMonitor
Administer
Program
Client: Client: • Download Download
MetadataMetadata• Generate ProxyGenerate Proxy• Invoke Proxy Invoke Proxy
MethodsMethods
• Generate BindingGenerate Binding• Generate AddressGenerate Address• MonitorMonitor
Using Windows Communication FoundationUsing Windows Communication Foundation(Service Programmer) Define Contracts(Service Programmer) Define Contracts
[DataContract(Name=“ProspectiveDeal”,Namespace=“WoodgroveBank”)]public class Deal{ [DataMember(Name=“StockSymbols”)] public string[] Symbols;
[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 Using the Windows Communication Communication
FoundationFoundation
Using the Windows Using the Windows Communication Communication
FoundationFoundation
ContractsContracts
StructuralStructuralDataContractMessageContract
BehavioralBehavioralServiceContractOperationContractFaultContract
Program
c E
n
d
p
o
i
n
t
Structural Contracts: Data Structural Contracts: Data ContractsContracts
Program
c E
n
d
p
o
i
n
t
[DataContract]public class book{…}
[DataContract]public class magazine{…}
[DataContract][KnownType(typeof(Book))][KnownType(typeof(Magazine))]public class PublishedItem{
[DataMember]object catalog;[DataMember]DateTime publicationDate;
}
Uncertainty/Polymorphism:Uncertainty/Polymorphism:The other use for the KnownType attribute
Structural Contracts: Data Structural Contracts: Data ContractsContracts
Program
c E
n
d
p
o
i
n
t
[DataContract]public class book{…}
[DataContract]public class magazine{…}
[DataContract][KnownType(typeof(Book))][KnownType(typeof(Magazine))]public class LibraryCatalog{
[DataMember]System.Collections.Hashtable catalog;
}
Dealing with collections:Dealing with collections:Use the KnownType attribute
Structural Contracts: Message Structural Contracts: Message ContractsContracts
Program
c E
n
d
p
o
i
n
t
[DataContract]public class PurchaseOrder{
[DataMember]public Customer customer;[DataMember]public Item[] items;
}
[MessageContract] public class PurchaseOrderMessage{ [MessageHeader] public int Number; [MessageBody(Order=1)] public PurchaseOrder Order;}
Defines the message structure on the Defines the message structure on the wirewire
The MessageBody is typically a The MessageBody is typically a DataContractDataContract
For custom SOAP headersFor custom SOAP headers
Using Windows Communication FoundationUsing Windows Communication Foundation(Service Programmer) Implement Contracts(Service Programmer) Implement Contracts
[ServiceContract(Name=“DealService”,Namespace=“WoodgroveBank”)]public interface IDeal{ … }
public class DealAnalyzer: IDeal{ Analysis IDeal.AnalyzeDeal(Deal dealToAnalyze) { … return Analysis; }
void IDeal.ExecuteDeal(Deal dealToExecute) { … return; }}
Behavioral Contracts: Service Behavioral Contracts: Service ContractsContracts
c E
n
d
p
o
i
n
t
[ServiceContract]public interface IOrderEntry{ [OperationContract(IsOneWay=true)] void PlaceOrder(PurchaseOrder order);}
[ServiceContract]public interface IExtendedOrderEntry: IOrderEntry{ [OperationContract] PurchaseOrder GetOrder(String orderIdentifier);}
InheritanceInheritancefor versioningfor multiple contracts at one endpoint
Program
Behavioral Contracts: Service Behavioral Contracts: Service ContractsContracts
c E
n
d
p
o
i
n
t
[ServiceContract][DataContractFormat(Style=OperationFormatStyle.Document)] //Or Rpcpublic interface IOrderEntry{ …}
[ServiceContract][XmlSerializerFormat(Style=OperationFormatStyle.Document,Use=OperationFormatUse.Literal)] //Or Encodedpublic interface IOrderEntry{ …}
Controlling how structural Controlling how structural contracts serializecontracts serialize
Program
Duplex typeDuplex type
Behavioral Contracts: Service Behavioral Contracts: Service ContractsContracts
c E
n
d
p
o
i
n
t
[ServiceContract(Session=true,CallbackContract=typeof(IOrderEntryCallback))]public interface IOrderEntry{ [OperationContract(IsOneWay = true)] void PlaceOrder(PurchaseOrder order);}
[ServiceContract]public interface IOrderEntryCallback{ [OperationContract(IsOneWay = true)] void PlaceOrderCompleted(PurchaseOrderStatus orderStatus);}
Program
Behavioral Contracts: Operation Behavioral Contracts: Operation ContractsContracts
c E
n
d
p
o
i
n
t
[ServiceContract]public interface IOrderEntry{ [OperationContract(IsOneWay=true)] void PlaceOrder(PurchaseOrder order);}
Use the Use the OperationContractAttributeOperationContractAttribute properties to properties to control the translation of the method signature into control the translation of the method signature into WSDL: WSDL:
The The AsyncPatternAsyncPattern property indicates that the property indicates that the operation is implemented asynchronously using a operation is implemented asynchronously using a Begin/End method pair.Begin/End method pair.The The IsOneWayIsOneWay property indicates that the operation property indicates that the operation only consists of a single input message. The only consists of a single input message. The operation has no associated output message.operation has no associated output message.The The IsInitiatingIsInitiating property specifies whether this property specifies whether this operation can be the initial operation in a session.operation can be the initial operation in a session.The The IsTerminatingIsTerminating property specifies whether WCF property specifies whether WCF attempts to terminate the current session after the attempts to terminate the current session after the operation completes.operation completes.The The ActionAction property specifies the action that property specifies the action that uniquely identifies this operation. WCF dispatches uniquely identifies this operation. WCF dispatches request messages to methods based on their action.request messages to methods based on their action.The The ReplyActionReplyAction property specifies the action of the property specifies the action of the reply message for the operation.reply message for the operation.
Program
Behavioral Contracts: Operation Behavioral Contracts: Operation ContractsContracts
c E
n
d
p
o
i
n
t
[ServiceContract]public interface MyContract{ [OperationContract(IsOneWay = true,
Action="urn:crud:insert")] void ProcessInsertMessage(Message message);
[OperationContract(IsOneWay = true, Action="urn:crud:update")]
void ProcessUpdateMessage(Message message);
[OperationContract(IsOneWay = true, Action="urn:crud:delete")]
void ProcessDeleteMessage(Message message);
[OperationContract(IsOneWay = true, Action="*")] void ProcessUnrecognizedMessage(Message message); }
Action PropertyAction Propertyuse a wildcard action to provide a
default message handlerProgram
Behavioral Contracts: Fault ContractsBehavioral Contracts: Fault Contracts
c E
n
d
p
o
i
n
t
[DataContract]public class MyFault{ [DataMember] string Reason = null;}
[ServiceContract]public interface IOrderEntry{ [OperationContract] [FaultContract(typeof(MyFault))] PurchaseOrder GetOrder(String orderIdentifier); }
public class OrderEntry: IOrderEntry{ public PurchaseOrder GetOrder(string orderIdentifier) { try{…}
catch(Exception exception){ MyFault theFault = new MyFault(); theFault.Reason = “Some Reason”; throw new FaultException<MyFault>(theFault);}
}}
Behavioral Contracts: Fault ContractsBehavioral Contracts: Fault Contracts
c E
n
d
p
o
i
n
t
[DataContract(Name=”MyFault”)]public class ClientFault{
[DataMember]string Reason = null;
}
…
try{
PurchaseOrder order = Service.GetOrder(orderIdentifier);}catch (FaultException<ClientFault> clientFault){
Console.WriteLine(clientFault.Reason);}
Client view:Client view:
Program
Using Windows Communication FoundationUsing Windows Communication Foundation(Service Programmer) Provide Host(Service Programmer) Provide Host
[ServiceContract(Name=“DealService”,Namespace=“WoodgroveBank”)]public interface IDeal{ … }
public class DealAnalyzer: Ideal{ … }
public class Program{ static void Main(string[] args) { using (ServiceHost host = ServiceHost(typeof(DealAnalyzer))) { host.Open();
Console.WriteLine(“The service is running."); Console.ReadLine(); }
finally{
host.Close();}
}}
Using Windows Communication FoundationUsing Windows Communication Foundation(Client Programmer) Download Metadata(Client Programmer) Download Metadata
(Client Programmer) Generate Typed Proxy(Client Programmer) Generate Typed Proxy
(Client Administrator) Generate Address(Client Administrator) Generate Address
(Client Administrator) Generate Binding(Client Administrator) Generate Binding
(Client Programmer) Invoke Typed Proxy (Client Programmer) Invoke Typed Proxy Methods Methods
SvcUtil.exe “http://localhost:8080/Deals/AnalysisService” /out:DealAnalysisProxy.cs /config: app.config
Deal deal = new Deal();…
using(DealAnalysisProxy analysisProxy = new DealAnalysisProxy(“DealAnalyzer”){ analysis = analysisProxy.AnalyzeDeal(deal);}finally{ analysisProxy.Close();}
Service Implementation: HostingService Implementation: Hosting
c E
n
d
p
o
i
n
t
Service
WCF services can be hosted in WCF services can be hosted in any .Net Application Domainany .Net Application Domain
This provides many options This provides many options out of the box for rich client out of the box for rich client applications (WPF or applications (WPF or WinForms), Windows Services, WinForms), Windows Services, IIS (WAS)IIS (WAS)
Choosing the hosting model Choosing the hosting model depends on the requirements depends on the requirements of your service and of your service and applicationsapplications
Program
Service Implementation: HostingService Implementation: Hosting
c E
n
d
p
o
i
n
t
[ServiceContract]public interface ILenderService {…}
internal class LenderService: ILenderService {…}
public class Program{ static void Main(string[] args) { using (ServiceHost host = ServiceHost(typeof(LenderService))) { host.Open(); Console.WriteLine(“The service is running."); Console.ReadLine();
} }}
Service
In standalone executablesIn standalone executables
Program
Program
Service Implementation: HostingService Implementation: Hosting
c E
n
d
p
o
i
n
t
Service
In an Managed Windows ServiceIn an Managed Windows ServiceBenefits:
Process lifetime controlled by O/SBuilt-in Service Control Manager
[ServiceContract]public interface ILenderService {…}
internal class LenderService: ILenderService {…}
public partial class MyManagedService : ServiceBase{ private ServiceHost host = null;
public MyNTService(){ InitializeComponent(); }
protected override void OnStart(string[] args) {
this.host = new ServiceHost(typeof(LenderService ));service.Open();
}
protected override void OnStop() {
host.Close(); }}
Service Implementation: HostingService Implementation: Hosting
c E
n
d
p
o
i
n
t
//LenderService.svc<%@Service Class="MyNamespace.LenderService" %><%@Assembly Name=“LenderServiceAssembly" %>
Service
IIS 5.1 & 6 support HTTP only IIS 5.1 & 6 support HTTP only
Windows Activation Services Windows Activation Services supports HTTP, TCP, Named Pipessupports HTTP, TCP, Named Pipes
WAS also provides activation of WAS also provides activation of service classes on the arrival of a service classes on the arrival of a requestrequest
//LenderService.csusing System.ServiceModel;
namespace MyNamespace{
[ServiceContract]public interface ILender {…}
internal class LenderService: ILender {…}}
Program
Deploy
BindingsBindings
c E
n
d
p
o
i
n
t
Service
Bindings = Bindings = Transports +Encoders +Protocols
b
Windows Communication Foundation Windows Communication Foundation ArchitectureArchitecture
User CodeUser Code User CodeUser Code
Typed ProxyTyped Proxy DispatcherDispatcher
ProtocolProtocol ProtocolProtocol
EncodingEncoding EncodingEncoding
TransportTransport TransportTransport
MessageMessage
Binding
Binding
Deploy
Bindings: TransportsBindings: Transports
c E
n
d
p
o
i
n
t
Service
HTTPHTTP
TCPTCP
Named PipesNamed Pipes
MSMQMSMQ
b
Binding Options: The Standard BindingsBinding Options: The Standard Bindings
Inte
rop
.In
tero
p.
Secu
ritySecu
rity
Sessio
nSessio
n
Tra
nsa
ction
Tra
nsa
ction
ss Duple
xD
uple
x
BasicHttpBindingBasicHttpBinding BP 1.1BP 1.1 TT
WsHttpBindingWsHttpBinding WSWS T | ST | S XX XX
WsDualHttpBindingWsDualHttpBinding WSWS T | ST | S XX XX XX
NetTcpBindingNetTcpBinding .NET.NET T | ST | S XX XX XX
NetNamedPipesBindingNetNamedPipesBinding .NET.NET T | ST | S XX XX XX
NetMsmqBindingNetMsmqBinding .NET.NET T | ST | S XX XX
MsmqIntegrationBindingMsmqIntegrationBinding .NET.NET TT
NetPeerTcpBindingNetPeerTcpBinding .NET.NET T | ST | S XX
T = Transport Security T = Transport Security || S = WS-Security Message Security S = WS-Security Message Security
Deploy
Bindings: EncodingBindings: Encoding
c E
n
d
p
o
i
n
t
Service
TextTextfor interoperability
BinaryBinaryfor hi-speed WCF-to-WCF
MTOM MTOM Message Transmission
Optimization Protocolfor incorporating binary attachments
b
Deploy
Bindings: MTOM EncodingBindings: MTOM Encoding
c E
n
d
p
o
i
n
t
Service
b
Problem: How to send binary data to a service in SOAP?Solution One:
1. SOAP is XML
2. XML provides Base64 Encoding
Express binary data in Base64
Embed in SOAP XML document
Snag:
Base64 encoding increases size by 1.33
Deploy
Bindings: MTOM EncodingBindings: MTOM Encoding
c E
n
d
p
o
i
n
t
Service
b
Problem: How to send binary data to a service in SOAP?Solution Two:
1. Put the XML of the SOAP message
2. … and the binary data into a MIME doc
3. Put a link in the SOAP to the binary data
Snag:
Encrypting the SOAP misses the binary data
Deploy
Bindings: MTOM EncodingBindings: MTOM Encoding
c E
n
d
p
o
i
n
t
Service
b
Problem: How to send binary data to a service in SOAP?MTOM Solution:
1. Express the binary data in Base64
2. Incorporate into SOAP XML
3. Encrypt SOAP document
4. Take the binary data out of the document
5. Convert it back out of Base64
6. Put SOAP & binary data into a MIME doc
7. Put a link in the SOAP to the binary data
Bindings: MTOM EncodingBindings: MTOM Encoding
c E
n
d
p
o
i
n
t
Service
b
WCF ImplementationWCF ImplementationSimply select MTOM as the encoding
All byte[] and Stream data gets “MTOM’d”
MTOM transmits an XML message as a MIME MTOM transmits an XML message as a MIME messagemessage
One MIME part that contains the XML in textual form
The other MIME parts that contain the binary data that has been optimized
The other MIME parts of the message are not encoded as text but transmitted separately as binary data.
The textual XML MIME part refers to the other, binary MIME parts in various places
This is equivalent to this binary data being included in the textual XML
The entire MIME message forms one XML infoset.
Bindings: ProtocolsBindings: Protocols
c E
n
d
p
o
i
n
t
Service
Might include,Might include,
WS-SecurityWS-Reliable MessagingWS-Coordination and Transaction
b
Deploy
BindingsBindings
c E
n
d
p
o
i
n
t
Service
Binding options: Binding options: Select a standard bindingCustomize a standard bindingDefine a custom binding
Configuring bindingsConfiguring bindingsConfigure in a configuration fileCreate and configure in code
b
Deploy
Using Windows Communication FoundationUsing Windows Communication Foundation
(Service Administrator) Configure Binding(Service Administrator) Configure Binding
(Service Administrator) Configure Address(Service Administrator) Configure Address
<!--App.Config (hosted in .NET Assembly) or Web.Config (hosted in IIS)--><configuration> <system.serviceModel> <services> <service serviceType=“DealAnalyzer”>
<endpoint address=“http://localhost:8080/Deals/AnalysisService” binding=“wsHttpBinding” contract=“IDeal”/>
</service> </services> </system.serviceModel></configuration>
Binding Options: The Standard BindingsBinding Options: The Standard Bindings
Selecting a standard bindingSelecting a standard binding
<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 BindingsBinding 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 BindingsBinding Options: Custom Bindings
public static void Main(string[] args){ ServiceHost host = new ServiceHost(typeof(MathService), “net.tcp://localhost/8080/MathService/”);
ReliableSessionBindingElement r = new ReliableSessionBindingElement(); r.AdvancedFlowControl = true;
SecurityBindingElement s = AsymmetricSecurityBindingElement.CreateKerberosBinding();
HttpTransportBindingElement t = new HttpTransportBindingElement(); t.MaxMessageSize = long.MaxValue;
TextMessageEncodingBindingElement e = new TextMessageEncodingBindingElement();
CustomBinding binding = new CustomBinding(new BindingElement[]{r,s,t,e});
EndpointAddress address = “net.tcp://localhost/8080/Math/”; host.AddEndpoint(typeof(IMath), binding, address);
host.Open();}
In code: In code:
Binding Options: Custom BindingsBinding Options: Custom Bindings
<?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>
In configuration: In configuration:
SecuritySecurity
WCF Security in a NutshellWCF Security in a Nutshell
WCF security does two thingsWCF security does two thingsSecures message exchange between entitiesSecures access to resources by entities
EntityEntity == person, company, software, … == person, company, software, …
ResourceResource == file, service, operation, … == file, service, operation, …
Messaging Security RequirementsMessaging Security Requirements
ConfidentialityConfidentiality
IntegrityIntegrity
AuthenticationAuthentication
AuthorizationAuthorization
Auditing Auditing
CredentialCredential
ClaimsClaimsInformation about an entityUsed to control access to resources
IssuerIssuerCertifies claims in the credential
Proof of possessionProof of possessionHow an entity proves it provided the claims
Credential ExamplesCredential Examples
AliceAlice
MyDomain\AliceMyDomain\Alice
Subject: CN=AliceSubject: CN=AliceIssuer: SomeCAIssuer: SomeCAValidFrom: 2005-09-13ValidFrom: 2005-09-13ValidUntil: 2005-09-16ValidUntil: 2005-09-16
UsernameUsername
KerberosKerberos
CertificateCertificate
WCF Security ModelWCF Security Model
Based on credentials and claimsBased on credentials and claims
Can satisfy security requirementsCan satisfy security requirements
Secure by defaultSecure by default
Consistent across bindingsConsistent across bindings
Consistent across credentialsConsistent across credentials
Transport SecurityTransport Security
Security requirements satisfied atSecurity requirements satisfied attransport layertransport layer
AdvantagesAdvantagesPerformance benefitsCommon implementation
DisadvantagesDisadvantagesRestricted claim typesNo security off the wire
Transport SecurityTransport Security
<endpoint address=“https://localhost/calculator" binding=“basicHttpBinding“
bindingConfiguration=“Binding1” contractType="ICalculator" />
<basicHttpBinding> <binding configurationName="Binding1">
<security mode="Transport"> <transport clientCredentialType="None"/>
</security></binding>
</basicProfileBinding>
Message SecurityMessage Security
Security requirements satisfied atSecurity requirements satisfied atmessage layermessage layer
AdvantagesAdvantagesMore credential typesExtensibleSecuring selected parts of messagesEnd-to-end security
DisadvantagesDisadvantagesStandards and usage still solidifying Performance impact
Message SecurityMessage Security
<endpoint address=“http://localhost/calculator" binding=“wsHttpBinding“
bindingConfiguration=“Binding1” contractType="ICalculator" />
<wsHttpBinding> <binding configurationName="Binding1">
<security mode="Message"> <message clientCredentialType=“Windows"/></security>
</binding></wsHttpBinding>
Mixed ModeMixed Mode
Compromise between Transport and Compromise between Transport and Message SecurityMessage Security
Transport layer satisfies integrity and Transport layer satisfies integrity and confidentiality requirements confidentiality requirements
Performance benefits
Message layer carries claimsMessage layer carries claimsRich credentials, extensibility
Mixed Mode SecurityMixed Mode Security
<endpoint address=“https://localhost/calculator" binding=“wsHttpBinding“
bindingConfiguration=“Binding1” contractType="ICalculator" />
<wsHttpBinding> <binding configurationName="Binding1">
<security mode="TransportWithMessageCredential"> <message clientCredentialType=“Windows"/></security>
</binding></wsHttpBinding>
Username/PasswordUsername/Password
Console.WriteLine(" Enter username[domain\\user]:");string username = Console.ReadLine();Console.WriteLine(" Enter password:");string password = Console.ReadLine(); CalculatorProxy proxy = new CalculatorProxy();proxy.ChannelFactory.Credentials.
UserNamePassword.UserName = username;proxy.ChannelFactory.Credentials.
UserNamePassword.Password = password;
ImpersonationImpersonation
[OperationBehavior(Impersonation=ImpersonationOption.Required)]
public double Add(double n1, double n2){ return n1 + n2;}
public double Add(double n1, double n2){ using (ServiceSecurityContext.Current. WindowsIdentity.Impersonate()) { return n1+n2; }}
PrincipalPermissionPrincipalPermission
[PrincipalPermission(SecurityAction.Demand, Role = "Builtin\\Administrators")]public double Add(double n1, double n2){ double result = n1 + n2; return result;}
<behaviors> <behavior configurationName="CalculatorServiceBehavior"> <serviceAuthorization
principalPermissionMode="UseWindowsGroups" /> </behavior></behaviors>
Federated CredentialsFederated Credentials
ServiceService
Credential IssuerCredential Issuer
ClientClient
I’m AliceI’m Alice(X.509)(X.509)
Here’s a Here’s a CredentialCredential
(SAML)(SAML)
I’m AliceI’m Alice
(SAML)(SAML)
Trust RelationshipTrust Relationship
Federated CredentialsFederated Credentials
Issued by third partyIssued by third party
Based on provided credentialsBased on provided credentials
Supports arbitrary credentialsSupports arbitrary credentials
Benefits:Benefits:Facilitates trust relationships across organizationsDelegation of claim checks to dedicated sourcesRich credential support
ReliabilityReliability
Challenges Of Reliable Distributed Challenges Of Reliable Distributed SystemsSystems
Communication Communication IssuesIssues
Network unavailableNetwork unavailable
Connection dropsConnection drops
Network loses Network loses messagesmessages
Messages may arrive Messages may arrive out of orderout of order
Processing IssuesProcessing IssuesMessages lost when Messages lost when processing failsprocessing failsInterrelated messages Interrelated messages processed individuallyprocessed individuallyFailure may leave the Failure may leave the distributed system in an distributed system in an inconsistent stateinconsistent stateMessages can’t be Messages can’t be retried without side retried without side effectseffects
SessionsSessions
ChannelChannel
Service Instance
ChannelChannel
Proxy
SessionSessionSessionSession
Reliable Sessions Reliable Sessions AssurancesAssurances
Messages are delivered exactly once, in the same Messages are delivered exactly once, in the same order as they were sentorder as they were sent
Alternatively, you can choose to have them delivered in order in which they were received
Resilient toResilient toTransport disconnectionsSOAP or transport intermediary failures
FeaturesFeaturesConnection verification and maintenanceCongestion and flow control
Reliable SessionsReliable SessionsEnablingEnabling
Provided on Standard BindingsProvided on Standard BindingsnetTcpBinding (off by default)
wsHttpBinding (off by default)
wsDualHttpBinding (always on)
Can be added to any custom bindingCan be added to any custom binding
<bindings><customBinding>
<binding configurationName=”ReliabilityHTTP”><reliableSession/><httpTransport/>
</binding></customBinding>
</bindings>
Keeping It ConsistentKeeping It Consistent
Atomic Transactions versus CompensationAtomic Transactions versus Compensation
Trading off coupling and complexityTrading off coupling and complexityAtomic Transactions: simpler to develop, negative perf impact, tighter couplingCompensation: more complex to develop, better perf, looser coupling
Both have their placeBoth have their placeChoose the right model for the situation
Transactions: ParticipationTransactions: Participation
[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);
}
Interface DefinitionInterface Definition
Transactions: InteractionTransactions: Interaction
[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(); } }
Service ProgrammerService Programmer
Transactions: UsageTransactions: Usage
TransactionScope transaction;using (scope = new TransactionScope()){ proxyForServiceOne.Transfer1(AccountOne, AccountTwo, amount); proxyForServiceTwo.Transfer1(AccountThree,AccountFour,amount); UpdateLocalCache(AccountOne, AccountTwo, amount); scope.Complete(); }
Client ProgrammerClient Programmer
Transactions: ControlTransactions: Control
<bindings> <wsHttpBinding> <binding configurationName="SampleBinding“ transactionFlow=“true" /> </binding> </wsHttpBinding></bindings>
Service AdministratorService Administrator
How Queues WorkHow Queues Work
Messa
ge
Messa
ge
Mess
ag
eM
ess
ag
e
CallerCaller ServiceService
QueueQueueQueueQueue
QueuesQueues
Increase availabilityIncrease availabilityMask network or service unavailability
Support scale outSupport scale outMultiple readers from a single queue
Provide load levelingProvide load levelingHandle average, not peak load
Are a building block for compensating transactionsAre a building block for compensating transactionsReliable, durable messaging to capture distributed state changesNeed to compensate for errors
How Queues WorkHow Queues Work
MessageMessage MessageMessage
CallerCaller ServiceService
Dead LetterDead LetterQueueQueue
QueueQueue
Poison Poison QueueQueue
QueueQueue
Queue EndpointQueue Endpoint
<endpoint address ="net.msmq://MyServer/private$/MyQueue/” binding="netMsmqBinding" bindingConfiguration ="MyQueueBinding" contract="IPurchaseOrder" />
QueuesQueuesFailure compensationFailure compensation
Set up compensation services on the Set up compensation services on the sending and receiving sidessending and receiving sides<binding configurationName="MyQueueBinding“
... timeToLive="0:2:0" deadLetterQueue= "net.msmq://MyClient/private/myCustomDLQ"/>
<endpoint address ="net.msmq://MyServer/private/MyQueue;poison/” bindingSectionName="netMsmqBinding" bindingConfiguration ="MyQueueBinding" contractType="Queue.IPurchaseOrder" />
Configuring Service RetriesConfiguring Service Retries
<netMsmqBinding> <binding configurationName="MyQueueBinding" msmqAuthenticationMode="None“ msmqProtectionLevel="None" maxRetries="2" maxRetryCycles="3" retryCycleDelay="0:0:10" rejectAfterLastRetry="false" /></netMsmqBinding>
10 seconds
3 retry cycles
2 retriesTo Poison Message Queue
1st attempt
WCF ManageabilityWCF Manageability
Configuration Configuration system which allows post-deployment system which allows post-deployment tuning and control of many aspects of servicetuning and control of many aspects of service
TracingTracing sources provide traces for service internals, sources provide traces for service internals, logged messages, activitieslogged messages, activities
Performance countersPerformance counters for key operation, security, for key operation, security, reliability, transaction statisticsreliability, transaction statistics
WMI ProviderWMI Provider allows scriptable query support for all allows scriptable query support for all aspects of running servicesaspects of running services
Windows Event LogWindows Event Log helps with diagnosis of helps with diagnosis of deployment problemsdeployment problems
Configuration Editor and Trace ViewerConfiguration Editor and Trace Viewer in the SDK in the SDK simplify common IT Pro taskssimplify common IT Pro tasks
Getting .NET 3.0Getting .NET 3.0
Built in to Windows Vista Built in to Windows Vista
Available for Windows XP SP2 & Windows Available for Windows XP SP2 & Windows Server 2003 SP1Server 2003 SP1
Release Candidate 1 available from:Release Candidate 1 available from:http://http://msdn.microsoft.com/windowsvista/getthebetamsdn.microsoft.com/windowsvista/getthebeta
Q3 Q4 Q2 Q3Q12006
Q22005
Q4 Q12007
B1 B2 V1RTMCTP RCxCTP
WCF SummaryWCF Summary
New communication infrastructure New communication infrastructure for .NET applicationsfor .NET applications
InteroperableInteroperable
Flexible Flexible
Easy to deploy and manageEasy to deploy and manage
ConclusionConclusion
.NET 3.0 provides a dramatic set of new .NET 3.0 provides a dramatic set of new featuresfeatures
Easier codingMore maintainableMore capability
Leverages existing tools and skillsLeverages existing tools and skillsPlugs into Visual Studio 2005Extension of the base framework