WCF Technical Drilldown

82
Windows Communication Windows Communication Framework Framework Technical Drilldown Technical Drilldown Jeff Brand Jeff Brand .NET Architect .NET Architect Microsoft – Minneapolis Microsoft – Minneapolis [email protected] [email protected] http://www.slickthought.net http://www.slickthought.net

Transcript of WCF Technical Drilldown

Page 1: 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

Page 2: WCF Technical Drilldown

AgendaAgenda

IntroIntro

The Basics The Basics

Understanding BindingsUnderstanding Bindings

Reliable MessagingReliable Messaging

SecuritySecurity

Page 3: WCF Technical Drilldown

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

Page 4: WCF Technical Drilldown

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

Page 5: WCF Technical Drilldown

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?

Page 6: WCF Technical Drilldown

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

Page 7: WCF Technical Drilldown

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

Page 8: WCF Technical Drilldown

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

Page 9: WCF Technical Drilldown

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

Page 10: WCF Technical Drilldown

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)}

Page 11: WCF Technical Drilldown

Using the Windows Using the Windows Communication Communication

FoundationFoundation

Using the Windows Using the Windows Communication Communication

FoundationFoundation

Page 12: WCF Technical Drilldown

ContractsContracts

StructuralStructuralDataContractMessageContract

BehavioralBehavioralServiceContractOperationContractFaultContract

Program

c E

n

d

p

o

i

n

t

Page 13: WCF Technical Drilldown

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

Page 14: WCF Technical Drilldown

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

Page 15: WCF Technical Drilldown

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

Page 16: WCF Technical Drilldown

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; }}

Page 17: WCF Technical Drilldown

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

Page 18: WCF Technical Drilldown

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

Page 19: WCF Technical Drilldown

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

Page 20: WCF Technical Drilldown

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

Page 21: WCF Technical Drilldown

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

Page 22: WCF Technical Drilldown

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);}

}}

Page 23: WCF Technical Drilldown

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

Page 24: WCF Technical Drilldown

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();}

}}

Page 25: WCF Technical Drilldown

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();}

Page 26: WCF Technical Drilldown

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

Page 27: WCF Technical Drilldown

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

Page 28: WCF Technical Drilldown

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(); }}

Page 29: WCF Technical Drilldown

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

Page 30: WCF Technical Drilldown

Deploy

BindingsBindings

c E

n

d

p

o

i

n

t

Service

Bindings = Bindings = Transports +Encoders +Protocols

b

Page 31: WCF Technical Drilldown

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

Page 32: WCF Technical Drilldown

Deploy

Bindings: TransportsBindings: Transports

c E

n

d

p

o

i

n

t

Service

HTTPHTTP

TCPTCP

Named PipesNamed Pipes

MSMQMSMQ

b

Page 33: WCF Technical Drilldown

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

Page 34: WCF Technical Drilldown

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

Page 35: WCF Technical Drilldown

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

Page 36: WCF Technical Drilldown

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

Page 37: WCF Technical Drilldown

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

Page 38: WCF Technical Drilldown

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.

Page 39: WCF Technical Drilldown

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

Page 40: WCF Technical Drilldown

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

Page 41: WCF Technical Drilldown

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>

Page 42: WCF Technical Drilldown

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.

Page 43: WCF Technical Drilldown

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>

Page 44: WCF Technical Drilldown

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:

Page 45: WCF Technical Drilldown

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:

Page 46: WCF Technical Drilldown

SecuritySecurity

Page 47: WCF Technical Drilldown

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, …

Page 48: WCF Technical Drilldown

Messaging Security RequirementsMessaging Security Requirements

ConfidentialityConfidentiality

IntegrityIntegrity

AuthenticationAuthentication

AuthorizationAuthorization

Auditing Auditing

Page 49: WCF Technical Drilldown

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

Page 50: WCF Technical Drilldown

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

Page 51: WCF Technical Drilldown

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

Page 52: WCF Technical Drilldown

Transport SecurityTransport Security

Security requirements satisfied atSecurity requirements satisfied attransport layertransport layer

AdvantagesAdvantagesPerformance benefitsCommon implementation

DisadvantagesDisadvantagesRestricted claim typesNo security off the wire

Page 53: WCF Technical Drilldown

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>

Page 54: WCF Technical Drilldown

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

Page 55: WCF Technical Drilldown

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>

Page 56: WCF Technical Drilldown

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

Page 57: WCF Technical Drilldown

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>

Page 58: WCF Technical Drilldown

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;

Page 59: WCF Technical Drilldown

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; }}

Page 60: WCF Technical Drilldown

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>

Page 61: WCF Technical Drilldown

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

Page 62: WCF Technical Drilldown

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

Page 63: WCF Technical Drilldown

ReliabilityReliability

Page 64: WCF Technical Drilldown

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

Page 65: WCF Technical Drilldown

SessionsSessions

ChannelChannel

Service Instance

ChannelChannel

Proxy

SessionSessionSessionSession

Page 66: WCF Technical Drilldown

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

Page 67: WCF Technical Drilldown

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>

Page 68: WCF Technical Drilldown

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

Page 69: WCF Technical Drilldown

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

Page 70: WCF Technical Drilldown

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

Page 71: WCF Technical Drilldown

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

Page 72: WCF Technical Drilldown

Transactions: ControlTransactions: Control

<bindings> <wsHttpBinding> <binding configurationName="SampleBinding“ transactionFlow=“true" /> </binding> </wsHttpBinding></bindings>

Service AdministratorService Administrator

Page 73: WCF Technical Drilldown

How Queues WorkHow Queues Work

Messa

ge

Messa

ge

Mess

ag

eM

ess

ag

e

CallerCaller ServiceService

QueueQueueQueueQueue

Page 74: WCF Technical Drilldown

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

Page 75: WCF Technical Drilldown

How Queues WorkHow Queues Work

MessageMessage MessageMessage

CallerCaller ServiceService

Dead LetterDead LetterQueueQueue

QueueQueue

Poison Poison QueueQueue

QueueQueue

Page 76: WCF Technical Drilldown

Queue EndpointQueue Endpoint

<endpoint address ="net.msmq://MyServer/private$/MyQueue/” binding="netMsmqBinding" bindingConfiguration ="MyQueueBinding" contract="IPurchaseOrder" />

Page 77: WCF Technical Drilldown

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" />

Page 78: WCF Technical Drilldown

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

Page 79: WCF Technical Drilldown

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

Page 80: WCF Technical Drilldown

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

Page 81: WCF Technical Drilldown

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

Page 82: WCF Technical Drilldown

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