26
1 Understanding Windows Understanding Windows Communication Foundation Communication Foundation Nick Page Nick Page [email protected] [email protected] Application Architect Application Architect Microsoft Ltd Microsoft Ltd

1 Understanding Windows Communication Foundation Nick Page [email protected] [email protected] Application Architect Microsoft Ltd

Embed Size (px)

Citation preview

1

Understanding Windows Understanding Windows Communication Foundation Communication Foundation

Nick Page Nick Page [email protected]@microsoft.com Application ArchitectApplication ArchitectMicrosoft LtdMicrosoft Ltd

Windows Communication Windows Communication FoundationFoundation• 1996 ISV1996 ISV

- Applications are IslandsApplications are Islands- Internal onlyInternal only- ISAM. Client/Server just becoming popularISAM. Client/Server just becoming popular- Interop using flat files – CSV, ftp, sharesInterop using flat files – CSV, ftp, shares- Microsoft offered simple proprietary technology-DCOMMicrosoft offered simple proprietary technology-DCOM

• 2006 ISV2006 ISV- Applications are part of solutionsApplications are part of solutions- Internal and External usersInternal and External users- ComposabilityComposability- SecuritySecurity- ScalabilityScalability- ““Interop” becomes core requirementInterop” becomes core requirement

Windows Communication Windows Communication FoundationFoundationWhich technology?Which technology?

RemotingRemoting

ASMX / WSEASMX / WSE

DCOMDCOM

System.MessagingSystem.Messaging

Enterprise ServicesEnterprise Services

MicrosoftMicrosoft

SocketsSockets

RMIRMI

JAX-RPCJAX-RPC

CORBACORBA

JMSJMS

EJBEJB

J2EEJ2EE

SocketsSockets

InteropInteropwith otherwith otherplatformsplatforms

ASMXASMX

Attribute- Attribute- BasedBased

ProgrammingProgramming

Enterprise Enterprise ServicesServices

WS-*WS-*ProtocolProtocolSupportSupport

WSEWSE

Message-Message-OrientedOriented

ProgrammingProgramming

System.MessagingSystem.Messaging

ExtensibilityExtensibilityLocation Location

transparencytransparency

.NET .NET RemotingRemoting

WCFWCF

Windows Communication Windows Communication FoundationFoundationUnified Programming ModelUnified Programming Model

6

Side-by-side co-Side-by-side co-existence with existing existence with existing distributed technologiesdistributed technologies

Seamless Seamless communication with communication with applications built on applications built on existing technologiesexisting technologies

Smooth upgrade of Smooth upgrade of existing code to WCFexisting code to WCF

Investment ProtectionInvestment ProtectionLeveraging Existing Microsoft Leveraging Existing Microsoft InvestmentsInvestments

ASMXASMX

ASMXASMX

ASMXASMX ESES WSE3WSE3

7

using System.Web.Services;     public class AccountingOperation{    public string AccountName;    public long Amount;        }

 public class Accounting {

    [WebMethod(TransactionOption=TransactionOption.RequiresNew)]    public int AddEntry(AccountingOperation debit,                        AccountingOperation credit)    {        // Add entry to internal accounting book        // return id.    }}

using System.ServiceModel;

[ServiceContract(FormatMode=ContractFormatMode.XmlSerializer)]

[OperationContract][OperationBehavior(AutoEnlistTransaction=true)]

//

//

ASMX to WCFASMX to WCF

8

Basic PrinciplesBasic Principles

1.1. Clients and Services Clients and Services

2.2. Endpoints Endpoints

3.3. A, B, C A, B, C

4.4. BehaviorsBehaviors

9

Client Service

Clients and ServicesClients and Services

10

Client Service

EndpointsEndpoints

EndpointEndpoint

Endpoint

Endpoint

11

Client Service

Address, Binding, ContractAddress, Binding, Contract

CBA

CBA

CBA

ABC

AddressWhere?

ContractWhat?

BindingHow?

12

Client Service

BehaviorsBehaviors

CBA

CBA

CBA

ABC

B BB

13

Selecting…Selecting…Address Binding BehaviourContract

HTTPHTTPTransportTransport

TCPTCPTransportTransport

NamedPipeNamedPipeTransportTransport

MSMQMSMQTransportTransport

CustomCustomTransportTransport

WS-SecurityWS-SecurityProtocolProtocol

WS-RMWS-RMProtocolProtocol

WS-CoordWS-CoordProtocolProtocol

DuplexDuplexChannelChannel

CustomCustomProtocolProtocol

http://...http://...

net.tcp://...net.tcp://...

net.pipe://...net.pipe://...

net.msmq://...net.msmq://...

xxx://...xxx://...

ThrottlingThrottlingBehaviorBehavior

MetadataMetadataBehaviorBehavior

Error Error BehaviorBehavior

CustomCustomBehaviorBehavior

InstancingInstancingBehaviorBehavior

ConcurrencyConcurrencyBehaviorBehavior

TransactionTransactionBehaviorBehavior

SecuritySecurityBehaviorBehavior

Request/Request/ResponseResponse

One-WayOne-Way

DuplexDuplex

net.p2p://...net.p2p://...PeerPeer

TransportTransport

Externally visible,

per-endpoint

Opaque, per-service,endpoint, or operation

14

Creating a ServiceCreating a Service

1.1. Define Define WhatWhat to Expose (Contract) to Expose (Contract)

2.2. Implement Contract Implement Contract

3.3. Define Endpoint(s)Define Endpoint(s)1.1. Define Define How How to Expose (Binding)to Expose (Binding)

2.2. Define Define WhereWhere to Expose (Address) to Expose (Address)

4.4. Host & Run Service Host & Run Service

15

CContractsontractsA Service is a CLR Class that A Service is a CLR Class that Implements One or More Service Implements One or More Service ContractsContracts[DataContract]

public class OrderDetail{ [DataMember] public string ItemName { get; set; } [DataMember] public Guid ItemId { get; set; } [DataMember] public double ItemPrice { get; set; }}

[ServiceContract]public interface IOrderProcessingService{ [OperationContract(IsOneWay = true)] void ProcessOrder(OrderDetail detail);}

class OrderProcessingService : IOrderProcessingService{ public void ProcessOrder(OrderDetail detail) { ... }}

[DataContract]public class OrderDetail{ [DataMember] public string ItemName { get; set; } [DataMember] public Guid ItemId { get; set; } [DataMember] public double ItemPrice { get; set; }}

[ServiceContract]public interface IOrderProcessingService{ [OperationContract(IsOneWay = true)] void ProcessOrder(OrderDetail detail);}

class OrderProcessingService : IOrderProcessingService{ public void ProcessOrder(OrderDetail detail) { ... }}

16

EncodingEncodingText, Binary, MTOM, CustomText, Binary, MTOM, Custom

Transport SelectionTransport SelectionTCP, HTTP, Named Pipes, Peer Channel, MSMQ, CustomTCP, HTTP, Named Pipes, Peer Channel, MSMQ, Custom

End-to-End SecurityEnd-to-End SecurityConfidentiality, Integrity, AuthN, AuthZ, Federation & InfocardConfidentiality, Integrity, AuthN, AuthZ, Federation & InfocardX.509, Username/Password, Kerberos, SAML, XrML, CustomX.509, Username/Password, Kerberos, SAML, XrML, Custom

End-to-End Reliable MessagingEnd-to-End Reliable MessagingTransport-Independent QoS (In-Order / Exactly-Once)Transport-Independent QoS (In-Order / Exactly-Once)

Volatile and Durable Queues for AvailabilityVolatile and Durable Queues for Availability

TransactionsTransactionsShared Transactions for “Synchronous” OperationsShared Transactions for “Synchronous” Operations

Transactional Queues for “Asynchronous” OperationsTransactional Queues for “Asynchronous” Operations

BBindinginding

17

AAddressesddresseshttp://microsoft.com:80/OrderService/WShttp://microsoft.com:80/OrderService/WS

https://microsoft.com:443/OrderService/BPhttps://microsoft.com:443/OrderService/BP

net.tcp://microsoft.com:808/OrderService/TCPnet.tcp://microsoft.com:808/OrderService/TCP

net.pipe://microsoft.com/OrderService/NPnet.pipe://microsoft.com/OrderService/NP

SchemeScheme http, https, net.tcp, http, https, net.tcp, net.pipenet.pipe

Host NameHost Name microsoft.commicrosoft.comPort (Optional) Port (Optional) **

80, 443, 80880, 443, 808

Base PathBase Path /OrderService//OrderService/Endpoint Endpoint AddressAddress

WS, BP, TCP, NPWS, BP, TCP, NP* - Port Does Not Apply to Named Pipes* - Port Does Not Apply to Named Pipes

18

HostingHosting

ServiceHostServiceHost allows for hosting allows for hosting anywhereanywhere

Console applicationsConsole applications

Windows applicationsWindows applications

Windows servicesWindows services

IIS provides an enterprise class IIS provides an enterprise class hosting environmenthosting environment

Edit a Edit a .svc.svc file and point at your service file and point at your service

HTTP transport in IIS 6.0HTTP transport in IIS 6.0

All transports in IIS 7.0 (Windows All transports in IIS 7.0 (Windows Activation Service)Activation Service)

19

ServiceHostServiceHost

Allows a WCF Service to be Hosted in Allows a WCF Service to be Hosted in Any AppDomainAny AppDomain

EXE, NT Service, WinForms, Avalon, etc.EXE, NT Service, WinForms, Avalon, etc.

public static void Main(string[] args){ ServiceHost host = new ServiceHost( typeof(OrderProcessingService);

host.BaseAddresses.Add( new Uri(“http://localhost/OrderService/”));

host.Open();}

public static void Main(string[] args){ ServiceHost host = new ServiceHost( typeof(OrderProcessingService);

host.BaseAddresses.Add( new Uri(“http://localhost/OrderService/”));

host.Open();}

20

Windows Windows Communication Communication FoundationFoundation

Svctraceviewer.exeSvctraceviewer.exe

Svcconfigeditor.exeSvcconfigeditor.exe

+ so much more+ so much more

21

© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

22

WCF Code MigrationWCF Code Migration

23

using System.Web.Services;     public class AccountingOperation{    public string AccountName;    public long Amount;        }

 public class Accounting {

    [WebMethod(TransactionOption=TransactionOption.RequiresNew)]    public int AddEntry(AccountingOperation debit,                        AccountingOperation credit)    {        // Add entry to internal accounting book        // return id.    }}

using System.ServiceModel;

[ServiceContract(FormatMode=ContractFormatMode.XmlSerializer)]

[OperationContract][OperationBehavior(AutoEnlistTransaction=true)]

//

//

ASMX to WCFASMX to WCF

24

public class Accounting : ServicedComponent{           

public void AddCreditEntry(string creditAccount, int creditAmount)   {          }}

using System.EnterpriseServices;

[ComponentAccessControl][SecureMethod][Transaction(TransactionOption.Required)]

[SecurityRole("Manager")]

using System.ServiceModel;

[ServiceContract]

[OperationContract][OperationBehavior(AutoEnlistTransaction=true)][PrincipalPermission(SecurityAction.Demand, Role="Managers")]

//

//////

//

Enterprise Services to WCFEnterprise Services to WCF

25

using Microsoft.Web.Services3;using Microsoft.Web.Services3;

[WebService][WebService]class HelloWorld class HelloWorld {{

      

[WebMethod][WebMethod]

        public string Hello (string text)public string Hello (string text) {{

MessageSignature signature = (MessageSignature)MessageSignature signature = (MessageSignature)RequestSoapContext.Current.Security.Elements[0];RequestSoapContext.Current.Security.Elements[0];if (!signature.SigningToken.Principal.IsInRoleif (!signature.SigningToken.Principal.IsInRole ("BUILTIN\Administrators"))("BUILTIN\Administrators"))

                        throw new AuthorizationException("Access denied");throw new AuthorizationException("Access denied");  

                return String.Format("Hello, {0}", text);return String.Format("Hello, {0}", text);        }}}}

Note: Configuration entry changes are requiredNote: Configuration entry changes are required

[OperationContract][OperationContract]

[PrincipalPermission(SecurityAction.Demand, null, "BUILTIN\[PrincipalPermission(SecurityAction.Demand, null, "BUILTIN\Administrators")]Administrators")]

using System.ServiceModel;using System.ServiceModel;

[ServiceContract][ServiceContract]

////

////

////

////////////

////////

WSE to WCFWSE to WCF

26

class MyQService class MyQService {{ public void ReceiveOrders()public void ReceiveOrders() {{ MessageQueue Queue = new MessageQueue(@".\private$\Books");MessageQueue Queue = new MessageQueue(@".\private$\Books"); XmlMessageFormatter formatter = new XmlMessageFormatter(XmlMessageFormatter formatter = new XmlMessageFormatter( new Type[] { typeof(System.Data.DataSet)});new Type[] { typeof(System.Data.DataSet)}); Queue.Formatter = formatter;Queue.Formatter = formatter; System.Messaging.Message msg = null;System.Messaging.Message msg = null; while((msg= Queue.Receive()) != null)while((msg= Queue.Receive()) != null) {{

DataSet booklist = (DataSet) msg.Body;DataSet booklist = (DataSet) msg.Body; ProcessOrders(booklist);ProcessOrders(booklist);

}} }}

Public void ProcessOrder(DataSet BookList) { ... }Public void ProcessOrder(DataSet BookList) { ... }

}}

using System.Messaging;using System.Messaging;using System.ServiceModel;using System.ServiceModel;

[ServiceContract][ServiceContract]

[OperationContract(IsOneWay = true)][OperationContract(IsOneWay = true)]

////

////

////

////////////////////////////

////////

////

System.Messaging to WCFSystem.Messaging to WCF

27

using System.Runtime.Remoting;     [Serializable]public class AccountingOperation{    public string AccountName;    public long Amount;        } public class Accounting {    public int AddEntry(AccountingOperation debit,                        AccountingOperation credit)    {        // Add entry to internal accounting book        // return id.    }}

using System.ServiceModel;

[ServiceContract]

[OperationContract]

: MarshalByRefObject

//

//

.NET Remoting to WCF.NET Remoting to WCF