wcf architecture overview

70
Thursday, June 16, 2022 Thursday, June 16, 2022 Arbind Arbind WCF Architecture WCF Architecture Overview Overview

Upload: arbind-tiwari

Post on 22-Apr-2015

2.795 views

Category:

Documents


0 download

DESCRIPTION

This is a fundamental understanding of WCF services.

TRANSCRIPT

Page 1: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

WCF Architecture OverviewWCF Architecture Overview

Page 2: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

WCF ServiceWCF Service

A service exposes endpointsA service exposes endpoints

(Endpoint: a port to communicate with outside world)(Endpoint: a port to communicate with outside world)

Page 3: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

A ClientA Client

Exchanges messages with one or more Endpoints.Exchanges messages with one or more Endpoints.

May also expose an Endpoint to receive Messages from a Service in a duplex May also expose an Endpoint to receive Messages from a Service in a duplex message exchange pattern.message exchange pattern.

Page 4: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Endpoint: Has Endpoint: Has

1. An Address1. An Address

2. A Binding2. A Binding

3. A Contract3. A Contract

Page 5: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Address:Address:

A network location where the Endpoint resides.A network location where the Endpoint resides.

Represented by an EndpointAddress ClassRepresented by an EndpointAddress Class

EndpointAddress is a URI, a collection of AddressHeader and identityEndpointAddress is a URI, a collection of AddressHeader and identity

Page 6: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Bindings: HasBindings: Has

1. A name1. A name

2. A namespace2. A namespace

3. A collection of binding elements3. A collection of binding elements

Page 7: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Collection of binding elements:Collection of binding elements:

Each binding elements describe how to communicate with the end pointEach binding elements describe how to communicate with the end point

1. 1. TcpTransportBindingElementTcpTransportBindingElement indicates that the Endpoint indicates that the Endpoint will communicate with the world using TCP as the transport protocol.will communicate with the world using TCP as the transport protocol.

2. 2. ReliableSessionBindingElement ReliableSessionBindingElement indicates that the Endpoint indicates that the Endpoint uses reliable messaging to provide message delivery assurances.uses reliable messaging to provide message delivery assurances.

3. 3. SecurityBindingElementSecurityBindingElement indicates that the Endpoint uses indicates that the Endpoint uses SOAP message security.SOAP message security.

Page 8: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Contracts:Contracts: Refers to the collection of operations which specify what endpoint will Refers to the collection of operations which specify what endpoint will

communicate to out side worldcommunicate to out side world

Page 9: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

ContractDescriptionContractDescription class is used to describe WCF Contracts class is used to describe WCF Contracts and their operations. and their operations.

Each Contract Operation have OperationDescriptions and Each Contract Operation have OperationDescriptions and

each operationDescription have MessageDescription each operationDescription have MessageDescription

Page 10: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Duplex Contract:Duplex Contract: Defines two Logical OperationsDefines two Logical Operations 1. A set that the Service exposes for the Client to call 1. A set that the Service exposes for the Client to call

2. A set that the Client exposes for the Service to call2. A set that the Client exposes for the Service to call

Page 11: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Contract:Contract: HasHas

1. Name1. Name

2. Namespace2. Namespace

3. Identity3. Identity

Page 12: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Contract:Contract:

Page 13: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Behaviors:Behaviors:

Are types which modifies services or client functionalitiesAre types which modifies services or client functionalities

Page 14: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

ServiceBehaviorServiceBehavior is a type which implements is a type which implements

IServiceBehaviorIServiceBehavior and applies to service and applies to service

Page 15: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

ChannelBehaviorChannelBehavior is a type which implements is a type which implements

IChannelBehaviorIChannelBehavior and applies to client and applies to client

Page 16: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Service and Channel DescriptionsService and Channel Descriptions The ServiceDescription class describes a WCF Service including the The ServiceDescription class describes a WCF Service including the

Endpoints exposed by the Service, the Behaviors applied to the Endpoints exposed by the Service, the Behaviors applied to the Service, and the type (a class) that implements the Service. Service, and the type (a class) that implements the Service.

ServiceDescription is used to create metadata, code/config, and ServiceDescription is used to create metadata, code/config, and channels.channels.

Page 17: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Behavior:Behavior:

Page 18: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

ChannelDescriptionChannelDescription describes a WCF Client's Channel to a describes a WCF Client's Channel to a specific Endpointspecific Endpoint

ServiceDescription can have multiple endpoint but ChannelDescription have only one endpoint

Page 19: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

WCF Runtime:WCF Runtime:

The set of objects responsible for sending and receiving messages The set of objects responsible for sending and receiving messages

Page 20: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Message:Message:

The unit of data exchange between a Client and an Endpoint The unit of data exchange between a Client and an Endpoint

A message should be of SOAP message type and can be serialized A message should be of SOAP message type and can be serialized using the WCF binary format, text XML, or any other custom using the WCF binary format, text XML, or any other custom format.format.

Page 21: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Channels:Channels:

Channels are the core abstraction for sending Messages to and Channels are the core abstraction for sending Messages to and

receiving Messages from an Endpoint.receiving Messages from an Endpoint.

Page 22: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Two Category of channel:Two Category of channel:

1. Transport Channels handle sending or receiving opaque octet 1. Transport Channels handle sending or receiving opaque octet streams using some form of transport protocol such as TCP, UDP, streams using some form of transport protocol such as TCP, UDP, or MSMQ.or MSMQ.

2. Protocol Channels, implement a SOAP-based protocol by 2. Protocol Channels, implement a SOAP-based protocol by processing and possibly modifying messages.processing and possibly modifying messages.

Page 23: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Procedure to define WCF ServiceProcedure to define WCF ServiceStep1: Step1: Defining and Implementing a ContractDefining and Implementing a Contract

using System.ServiceModel; using System.ServiceModel;

[ServiceContract] [ServiceContract] public interface IMath public interface IMath {{

[OperationContract][OperationContract] int Add(int x, int y);int Add(int x, int y);

}}

Step2:Step2: Define a service classDefine a service classThis contract (interface IMath) is implemented to a class which becomes a This contract (interface IMath) is implemented to a class which becomes a

service classservice class

public class MathService : IMath public class MathService : IMath {{

public int Add(int x, int y) public int Add(int x, int y) { {

return x + y; return x + y; } }

} }

Page 24: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Step3:Step3: Defining Endpoints and Starting the Service Defining Endpoints and Starting the Service (endpoint can be defined in code or in config)(endpoint can be defined in code or in config)

In Code:In Code:public class WCFServiceApp public class WCFServiceApp { {

public void DefineEndpointImperatively() public void DefineEndpointImperatively() { {

//create a service host for MathService //create a service host for MathService ServiceHost sh = new ServiceHost(typeof(MathService));ServiceHost sh = new ServiceHost(typeof(MathService));//use the AddEndpoint helper method to //use the AddEndpoint helper method to //create the ServiceEndpoint and add it //create the ServiceEndpoint and add it //to the ServiceDescription //to the ServiceDescription sh.AddServiceEndpoint( typeof(IMath), sh.AddServiceEndpoint( typeof(IMath), //contract type new WSHttpBinding(), //contract type new WSHttpBinding(), //one of the built-in bindings "http://localhost/MathService/Ep1"); //one of the built-in bindings "http://localhost/MathService/Ep1"); //the endpoint's address //the endpoint's address //create and open the service runtime //create and open the service runtime sh.Open(); sh.Open();

} } public void DefineEndpointInConfig() public void DefineEndpointInConfig() { {

//create a service host for MathService //create a service host for MathService ServiceHost sh = new ServiceHost (typeof(MathService)); ServiceHost sh = new ServiceHost (typeof(MathService)); //create and open the service runtime //create and open the service runtime sh.Open(); sh.Open();

} } } }

Page 25: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Endpoint in config file:Endpoint in config file:<!-- configuration file used by above code --> <!-- configuration file used by above code -->

<configuration <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

<system.serviceModel> <system.serviceModel>

<services> <services>

<!-- service element references the service type --> <!-- service element references the service type -->

<service type="MathService"> <service type="MathService">

<!-- endpoint element defines the ABC's of the endpoint --> <!-- endpoint element defines the ABC's of the endpoint -->

<endpoint address="http://localhost/MathService/Ep1" <endpoint address="http://localhost/MathService/Ep1" binding="wsHttpBinding" contract="IMath"/>binding="wsHttpBinding" contract="IMath"/>

</service> </service>

</services> </services>

</system.serviceModel> </system.serviceModel>

</configuration></configuration>

Page 26: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Step4: Step4: Sending Messages to the EndpointSending Messages to the Endpointusing System.ServiceModel; using System.ServiceModel;

//this contract is generated by svcutil.exe //this contract is generated by svcutil.exe

//from the service's metadata //from the service's metadata

public interface IMath public interface IMath

{ {

[OperationContract] [OperationContract]

public int Add(int x, int y) public int Add(int x, int y)

{ {

return x + y; return x + y;

} }

} }

//this class is generated by svcutil.exe //this class is generated by svcutil.exe

//from the service's metadata //from the service's metadata

//generated config is not shown here //generated config is not shown here

public class MathProxy : IMath public class MathProxy : IMath

{ ... }{ ... }

Continue……….Continue……….

Page 27: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

In the following code first way to send the message to endpoint is like In the following code first way to send the message to endpoint is like SendMessageToEndpointSendMessageToEndpoint part. This hides the channel creation which is happening part. This hides the channel creation which is happening behind the scenebehind the scene

Second way (Second way (SendMessageToEndpointUsingChannelSendMessageToEndpointUsingChannel) does it explicitly.) does it explicitly.

public class WCFClientApp public class WCFClientApp { {

public void SendMessageToEndpoint() public void SendMessageToEndpoint() { {

//this uses a proxy class that was //this uses a proxy class that was //created by svcutil.exe from the service's metadata //created by svcutil.exe from the service's metadata MathProxy proxy = new MathProxy(); MathProxy proxy = new MathProxy(); int result = proxy.Add(35, 7); int result = proxy.Add(35, 7);

} } public void SendMessageToEndpointUsingChannel() public void SendMessageToEndpointUsingChannel() { {

//this uses ChannelFactory to create the channel //this uses ChannelFactory to create the channel //you must specify the address, the binding and //you must specify the address, the binding and //the contract type (IMath) //the contract type (IMath) ChannelFactory<IMath> factory=new ChannelFactory<IMath>( new WSHttpBinding(), new ChannelFactory<IMath> factory=new ChannelFactory<IMath>( new WSHttpBinding(), new

EndpointAddress("http://localhost/MathService/Ep1")); EndpointAddress("http://localhost/MathService/Ep1")); IMath channel=factory.CreateChannel(); IMath channel=factory.CreateChannel(); int result=channel.Add(35,7); int result=channel.Add(35,7); factory.Close(); factory.Close();

} }

}}

Page 28: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Step5:Step5: Defining custom behaviorDefining custom behavior

We need to implement IServiceBehavior for service and IChannelBehavior for We need to implement IServiceBehavior for service and IChannelBehavior for clientclient

All behaviors can be applied imperatively by adding an instance of the All behaviors can be applied imperatively by adding an instance of the behavior to the ServiceDescription (or the ChannelDescription on the client behavior to the ServiceDescription (or the ChannelDescription on the client side). side).

ServiceHost sh = new ServiceHost(typeof(MathService)); ServiceHost sh = new ServiceHost(typeof(MathService)); sh.AddServiceEndpoint( typeof(IMath), new WSHttpBinding(), sh.AddServiceEndpoint( typeof(IMath), new WSHttpBinding(), "http://localhost/MathService/Ep1"); "http://localhost/MathService/Ep1");

//Add the behavior imperatively //Add the behavior imperatively

// InspectorBehavior is a custom behavior// InspectorBehavior is a custom behavior

InspectorBehavior behavior = new InspectorBehavior(); InspectorBehavior behavior = new InspectorBehavior(); sh.Description.Behaviors.Add(behavior); sh.Description.Behaviors.Add(behavior);

sh.Open(); sh.Open();

Page 29: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Secure Hosting and Deployment of WCF Services Secure Hosting and Deployment of WCF Services

Service host is a execution environment for service codeService host is a execution environment for service code

Service has to be hosted before deploymentService has to be hosted before deployment

Page 30: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Why host is required?Why host is required?

Provide security context for the execution of WCF serviceProvide security context for the execution of WCF service Providing a mechanism to configure the WCF serviceProviding a mechanism to configure the WCF service Providing a mechanism to monitor the statistics and health of WCF Providing a mechanism to monitor the statistics and health of WCF

serviceservice Provide rapid fail protection and tools for WCF service Provide rapid fail protection and tools for WCF service

managementmanagement

Page 31: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Type of hostType of host

1. Managed Application / Self Host1. Managed Application / Self Host

2. Managed Windows Service2. Managed Windows Service

3. IIS3. IIS4. WAS4. WAS

Page 32: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Criteria for Choosing a WCF Service HostCriteria for Choosing a WCF Service Host Consider following things before coming to conclusionConsider following things before coming to conclusion

A. Target Deployment PlatformA. Target Deployment Platform

B. Protocol to be supported by the serviceB. Protocol to be supported by the service

Page 33: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Example:Example:

If service needed to support HTTP, TCP, MSMQ and Named Pipe and If service needed to support HTTP, TCP, MSMQ and Named Pipe and platform is Windows longhorn server – IIS 7.0 with WAS should be platform is Windows longhorn server – IIS 7.0 with WAS should be usedused

If service needed to support HTTP and platform is Windows server If service needed to support HTTP and platform is Windows server 2003 – IIS 6.0 should be used2003 – IIS 6.0 should be used

if TCP, MSMQ and Named Pipe required to be supported and platform if TCP, MSMQ and Named Pipe required to be supported and platform is Windows server 2003 - Managed Windows Service can be usedis Windows server 2003 - Managed Windows Service can be used

If service need to support HTTP, TCP, MSMQ and Named Pipe If service need to support HTTP, TCP, MSMQ and Named Pipe protocols on Windows Vista – IIS 7.0 along with WAS should be protocols on Windows Vista – IIS 7.0 along with WAS should be usedused

On Windows XP, IIS 5.1 should be used if supported protocol is HTTP On Windows XP, IIS 5.1 should be used if supported protocol is HTTP and Windows service can be used for TCP, MSMQ and Named Pipeand Windows service can be used for TCP, MSMQ and Named Pipe

Page 34: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

How to select host?How to select host?

Managed Application / Self HostManaged Application / Self Host

Any .NET managed application can host a WCF service by creating an instance Any .NET managed application can host a WCF service by creating an instance of ServiceHost Class of ServiceHost Class

ServiceHost Class is a member of System.ServiceModel namespace ServiceHost Class is a member of System.ServiceModel namespace

(Hosting a Service in managed application is also called Self Hosting)(Hosting a Service in managed application is also called Self Hosting)

Page 35: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Point to note:Point to note: Self host does not provide features like message Self host does not provide features like message based activation, mechanism to monitor service health or service based activation, mechanism to monitor service health or service host resources or recycling of the service host process upon host resources or recycling of the service host process upon detection of error conditions.detection of error conditions.

And so:And so: This is useful in development environment but not in This is useful in development environment but not in production environmentproduction environment

Page 36: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

In Self Hosting, the Service Host has to be instantiated at the time of In Self Hosting, the Service Host has to be instantiated at the time of the managed application startup and closed before the managed the managed application startup and closed before the managed application shutdown. application shutdown.

Page 37: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

The security context in Self Host is the identity under which the The security context in Self Host is the identity under which the managed application runsmanaged application runs

Page 38: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

A WCF Service hosted in a managed application can be exposed over A WCF Service hosted in a managed application can be exposed over TCP, HTTP, HTTPS, Named Pipe and MSMQ protocols.TCP, HTTP, HTTPS, Named Pipe and MSMQ protocols.

Page 39: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Code sample for creating a Service Host in Code sample for creating a Service Host in managed applicationmanaged application

Using(ServiceHost serviceHost = new  ServiceHost(typeof(CalculatorService)))Using(ServiceHost serviceHost = new  ServiceHost(typeof(CalculatorService)))

{{

      //Open the Service Host to start receiving messages//Open the Service Host to start receiving messages

          serviceHost.Open();       serviceHost.Open();      

          // The service is now ready to accept requests  // The service is now ready to accept requests 

     …     …....

   …   …....

          // Close the ServiceHost to shutdown the service.// Close the ServiceHost to shutdown the service.

          serviceHost.Close();serviceHost.Close();

}}

Page 40: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

The base address and the endpoints for the service host have to be configured in the The base address and the endpoints for the service host have to be configured in the <services> sub section of the <system.serviceModel> section of the App.Config as <services> sub section of the <system.serviceModel> section of the App.Config as shown below:shown below:

<system.serviceModel><system.serviceModel>        <services><services>            <service <service                     name="SecureHosting.Samples.CalculatorService"name="SecureHosting.Samples.CalculatorService"                    behaviorConfiguration="CalculatorServiceBehavior">behaviorConfiguration="CalculatorServiceBehavior">                <host><host>                    <baseAddresses><baseAddresses>                        <add baseAddress="http://localhost:9000/SecureHostingSamples/service"/><add baseAddress="http://localhost:9000/SecureHostingSamples/service"/>                    </baseAddresses></baseAddresses>                </host></host>                <endpoint address=""<endpoint address=""                                    binding="wsHttpBinding"binding="wsHttpBinding"                                    contract="SecureHosting.Samples.ICalculator" />contract="SecureHosting.Samples.ICalculator" />                <endpoint address="mex"<endpoint address="mex"                                    binding="mexHttpBinding"binding="mexHttpBinding"                                    contract="IMetadataExchange" />contract="IMetadataExchange" />            </service></service>        </services></services>          <behaviors><behaviors>            <serviceBehaviors><serviceBehaviors>                <behavior name="CalculatorServiceBehavior"><behavior name="CalculatorServiceBehavior">                    <serviceMetadata httpGetEnabled="True"/><serviceMetadata httpGetEnabled="True"/>                    <serviceDebug includeExceptionDetailInFaults="True" /><serviceDebug includeExceptionDetailInFaults="True" />                </behavior></behavior>            </serviceBehaviors></serviceBehaviors>        </behaviors></behaviors>      </system.serviceModel></system.serviceModel>

Page 41: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Base Address and endpoint can also be configured Base Address and endpoint can also be configured programmatically instead of configuring in App.Config fileprogrammatically instead of configuring in App.Config file

// Create a ServiceHost for the CalculatorService type.// Create a ServiceHost for the CalculatorService type.  using (ServiceHost serviceHost = using (ServiceHost serviceHost =         new ServiceHost(typeof(CalculatorService),new new ServiceHost(typeof(CalculatorService),new             Uri("http://localhost:9000/SecureHostingSamples/service")))                Uri("http://localhost:9000/SecureHostingSamples/service")))                  {{                              //Configure the service with an end point //Configure the service with an end point                 serviceHost.AddServiceEndpoint(typeof(ICalculator), serviceHost.AddServiceEndpoint(typeof(ICalculator),                       new WSHttpBinding(), "");new WSHttpBinding(), "");                // Open the ServiceHost to start receiving messages// Open the ServiceHost to start receiving messages                  serviceHost.Open();serviceHost.Open();      …      …..     …     …..      …      …..            //Close the service host to shutdown the service//Close the service host to shutdown the service                serviceHost.Close ();serviceHost.Close ();}}

Page 42: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Managed Window ServiceManaged Window Service(A Window Service running under managed environment)(A Window Service running under managed environment)

Service can be installed using Installutil tool.Service can be installed using Installutil tool.

The service can be exposed to HTTP, TCP, MSMQ and Named Pipe protocolThe service can be exposed to HTTP, TCP, MSMQ and Named Pipe protocol

Page 43: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

The window service which host the service inherits from the The window service which host the service inherits from the ServiceBase class and also implements contractServiceBase class and also implements contract

Page 44: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Windows Service provides the facility to manage the lifecycle of the Windows Service provides the facility to manage the lifecycle of the

service via the Service Control Manager (SCM) consoleservice via the Service Control Manager (SCM) console

Page 45: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Windows Service Host does not provide a message based activationWindows Service Host does not provide a message based activation

Page 46: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Window service leverages the OnStart event to create service host Window service leverages the OnStart event to create service host and host closes on OnStop event.and host closes on OnStop event.

Page 47: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Security context can be configured using Installer Class with the help Security context can be configured using Installer Class with the help of ServiceProcessInstaller.of ServiceProcessInstaller.

Page 48: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Sample Code to create Managed Window ServiceSample Code to create Managed Window Servicepublic class CalculatorService : ServiceBase, ICalculatorpublic class CalculatorService : ServiceBase, ICalculator{{          public ServiceHost serviceHost = null;public ServiceHost serviceHost = null;            public static void Main()public static void Main()          {{                    ServiceBase.Run(new CalculatorService());ServiceBase.Run(new CalculatorService());          }}            public CalculatorService()public CalculatorService()          {{                    ServiceName = "WCFWindowsCalculatorService";ServiceName = "WCFWindowsCalculatorService";          }}            //Start the Windows service.//Start the Windows service.          protected override void OnStart(string[] args)protected override void OnStart(string[] args)          {{                    if (serviceHost != null)if (serviceHost != null)                    {{                                serviceHost.Close();serviceHost.Close();                    }}                      // Create a ServiceHost for the Service// Create a ServiceHost for the Service                      serviceHost = new ServiceHost(typeof(CalculatorService));serviceHost = new ServiceHost(typeof(CalculatorService));                        // Start Listening for the Messages// Start Listening for the Messages                      serviceHost.Open();serviceHost.Open();            }}                        //Stop the Windows Service//Stop the Windows Service            protected override void OnStop()protected override void OnStop()            {{                      if (serviceHost != null)if (serviceHost != null)                      {{                            serviceHost.Close();serviceHost.Close();                            serviceHost = null;serviceHost = null;                      }}            }}}}

Page 49: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

IISIISAllows the Services to be hosted in the App Domains inside the ASP.NET Allows the Services to be hosted in the App Domains inside the ASP.NET

worker processworker process

Supported IIS: 5.1, 6.0, 7.0 8.0(BETA)Supported IIS: 5.1, 6.0, 7.0 8.0(BETA)

(Only Http and Https can be handled)(Only Http and Https can be handled)

Page 50: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

IIS handles the service request in the same way as it handles web IIS handles the service request in the same way as it handles web requestrequest

Supports message based activation and service instance is created Supports message based activation and service instance is created only after receiving the first message.only after receiving the first message.

Page 51: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

The security context for the WCF Service hosted inside the ASP.NET The security context for the WCF Service hosted inside the ASP.NET worker process is provided by the service account under which the worker process is provided by the service account under which the worker process runs.worker process runs.

(Knowledge Sharing) (Knowledge Sharing)

WHAT WILL BE THE SECURITY TO BE IMPLEMENTED?WHAT WILL BE THE SECURITY TO BE IMPLEMENTED?

Page 52: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Hosting a service in IIS requires .SVC file to be createdHosting a service in IIS requires .SVC file to be created

If required a Custom Service Host we can create it using If required a Custom Service Host we can create it using System.ServiceModel.Activation.ServiceHostFactory ClassSystem.ServiceModel.Activation.ServiceHostFactory Class

(Virtual applications are created and DLLs and sources are deployed to the (Virtual applications are created and DLLs and sources are deployed to the physical path associated with the virtual application)physical path associated with the virtual application)

Page 53: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

The configuration for the service endpoints has to be defined in the The configuration for the service endpoints has to be defined in the Web.ConfigWeb.Config

The .SVC file should contain code like:The .SVC file should contain code like:

<<%@ServiceHost language=c# Debug="true" Service="%@ServiceHost language=c# Debug="true" Service="SecureHosting.Samples.CalculatorServiceSecureHosting.Samples.CalculatorService" %" %>>

Page 54: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Web.Config for IIS Host:Web.Config for IIS Host:

<system.serviceModel><system.serviceModel>        <services><services>            <service name="SecureHosting.Samples.CalculatorService"<service name="SecureHosting.Samples.CalculatorService"                              behaviorConfiguration="CalculatorServiceBehavior">behaviorConfiguration="CalculatorServiceBehavior">                <!-- This endpoint is exposed at the base address provided by host: <!-- This endpoint is exposed at the base address provided by host:

http://localhost/securehostingsamples/service.svc  -->http://localhost/securehostingsamples/service.svc  -->                <endpoint address=""<endpoint address=""                                    binding="wsHttpBinding"binding="wsHttpBinding"                                    contract="SecureHosting.Samples.ICalculator" />contract="SecureHosting.Samples.ICalculator" />                <endpoint address="mex"<endpoint address="mex"                                    binding="mexHttpBinding"binding="mexHttpBinding"                                    contract="IMetadataExchange" />contract="IMetadataExchange" />            </service></service>        </services></services>          <!--For debugging purposes set the includeExceptionDetailInFaults attribute to true--><!--For debugging purposes set the includeExceptionDetailInFaults attribute to true-->        <behaviors><behaviors>            <serviceBehaviors><serviceBehaviors>                <behavior name="CalculatorServiceBehavior"><behavior name="CalculatorServiceBehavior">                    <serviceMetadata httpGetEnabled="True"/><serviceMetadata httpGetEnabled="True"/>                    <serviceDebug includeExceptionDetailInFaults="True" /><serviceDebug includeExceptionDetailInFaults="True" />                </behavior></behavior>            </serviceBehaviors></serviceBehaviors>        </behaviors></behaviors>      </system.serviceModel></system.serviceModel>

Page 55: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

WAS (Windows Activation Service)WAS (Windows Activation Service)

WAS enables IIS 7.0 to leverage message based activation for WAS enables IIS 7.0 to leverage message based activation for protocols such as TCP, MSMQ and Named Pipes in addition to the protocols such as TCP, MSMQ and Named Pipes in addition to the HTTP protocolHTTP protocol

Available with Windows Vista and Windows Longhorn ServerAvailable with Windows Vista and Windows Longhorn Server

Service deployment process for IIS 7.0/WAS is same as discussed Service deployment process for IIS 7.0/WAS is same as discussed earlier for IIS hostearlier for IIS host

Page 56: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Note:Note:1. web sites need to be configured via the APPCMD utility to support 1. web sites need to be configured via the APPCMD utility to support

non HTTP protocolsnon HTTP protocols

2. To do this command shell must be started in “Run as 2. To do this command shell must be started in “Run as Administrator” modeAdministrator” mode

Page 57: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Command to run:Command to run:

%windir%\system32\inetsrv\appcmd.exe set site "Default Web Site" -+bindings.[protocol='net.tcp',bindingInformation='808:*'] FOR TCP

%windir%\system32\inetsrv\appcmd.exe set site "Default Web Site" -+bindings.[protocol='net.msmq',bindingInformation='*'] FOR MSMQ

%windir%\system32\inetsrv\appcmd.exe set site "Default Web Site" -+bindings.[protocol='net.pipe',bindingInformation='*'] FOR NAMED PIPE

Page 58: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

After running the command APPCMD updates configuration file for WAS After running the command APPCMD updates configuration file for WAS ApplicationHost.ConfigApplicationHost.Config

<system.applicationHost><system.applicationHost>

    <sites><sites>

        <site name="Default Web Site" id="1"><site name="Default Web Site" id="1">

            <bindings><bindings>

                <binding protocol="http" <binding protocol="http"

                                              bindingInformation="*:80:" />bindingInformation="*:80:" />

                <binding protocol="net.pipe" <binding protocol="net.pipe"

                                              bindingInformation="*" />bindingInformation="*" />

                <binding protocol="net.tcp" <binding protocol="net.tcp"

                                              bindingInformation="808:*" />bindingInformation="808:*" />

                <binding protocol="net.msmq" <binding protocol="net.msmq"

                                              bindingInformation="*" />bindingInformation="*" />

            </bindings></bindings>

        </site></site>

    </sites></sites>

</system.applicationHost></system.applicationHost>

Page 59: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

To enable the TCP protocol (in addition to the HTTP protocol) for the To enable the TCP protocol (in addition to the HTTP protocol) for the “SecureHostingSamples” application, the following command should be run “SecureHostingSamples” application, the following command should be run from an administrator shell:from an administrator shell:

%windir%\system32\inetsrv\appcmd.exe set app "Default Web %windir%\system32\inetsrv\appcmd.exe set app "Default Web Site/securehostingsamples" /enabledProtocols:http,net.tcpSite/securehostingsamples" /enabledProtocols:http,net.tcp

Page 60: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Selecting Binding:Selecting Binding:Criteria to select Bindings:Criteria to select Bindings:

1. Consider the deployment environment whether it is for Internet, Intranet, 1. Consider the deployment environment whether it is for Internet, Intranet, Federated Environment, Windows only or a Heterogeneous EnvironmentFederated Environment, Windows only or a Heterogeneous Environment

2. Security to be implemented2. Security to be implemented

3. Performance Issues3. Performance Issues

Page 61: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

A WCF service can be assigned:A WCF service can be assigned:1. Transport level security, 1. Transport level security,

2. Message level security or 2. Message level security or

3. A combination of transport and message level security.3. A combination of transport and message level security.

Page 62: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

A service can be defined with an authentication mode of A service can be defined with an authentication mode of

1. None, 1. None,

2. Username, 2. Username,

3. Windows, 3. Windows,

4. Certificates and 4. Certificates and

5. IssuedToken. 5. IssuedToken.

Authentication process between the client and the service includes the Authentication process between the client and the service includes the authentication of service to the client as well as the authentication of the authentication of service to the client as well as the authentication of the client to the service.client to the service.

Page 63: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Deploying a WCF Service over Windows Only IntranetDeploying a WCF Service over Windows Only IntranetIn Windows only Intranet, if all the service clients are WCF clients, the In Windows only Intranet, if all the service clients are WCF clients, the service can be deployed using NetTCPBinding and transport level security service can be deployed using NetTCPBinding and transport level security to achieve maximum performance.to achieve maximum performance.

(NetTCPBinding by default uses transport level security along with TCP (NetTCPBinding by default uses transport level security along with TCP channel and binary message encoding)channel and binary message encoding)

ClientCredentialType is set to Windows to enable Windows AuthenticationClientCredentialType is set to Windows to enable Windows Authentication

Code Sample:Code Sample:

<bindings><bindings>    <netTcpBinding><netTcpBinding>        <binding name="Binding1"><binding name="Binding1">                <security mode="Transport" /><security mode="Transport" />                      <transport <transport

clientCredentialType="Windows"  protectionLevel="EncryptAndSign"/>clientCredentialType="Windows"  protectionLevel="EncryptAndSign"/>                </security></security>        </binding></binding>    </netTcpBinding></netTcpBinding></bindings></bindings>

Page 64: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Interoperability with web servicesInteroperability with web services

The WCF service can be configured to use BasicHttpBinding with transport The WCF service can be configured to use BasicHttpBinding with transport level security. level security.

HTTP/GET metadata should be enabled for the service in the service behavior HTTP/GET metadata should be enabled for the service in the service behavior section.section.

Page 65: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Deploying a WCF Service over Internet or in a Heterogeneous EnvironmentDeploying a WCF Service over Internet or in a Heterogeneous Environment

((needs to potentially interact with the clients on non-windows platformsneeds to potentially interact with the clients on non-windows platforms))

--BasicHttpBinding or WSHttpBinding can be used depending upon the level of --BasicHttpBinding or WSHttpBinding can be used depending upon the level of conformance required with the commonly used security standards conformance required with the commonly used security standards

If interoperability is required with web service only BasicHttpBinding should be If interoperability is required with web service only BasicHttpBinding should be used.used.

Page 66: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

To support SOAP Message Security UserName Token Profile version 1.0, the To support SOAP Message Security UserName Token Profile version 1.0, the WCF service should be configured with BasicHttpBinding with security WCF service should be configured with BasicHttpBinding with security mode of TransportWithMessageCredential and client credential type of mode of TransportWithMessageCredential and client credential type of UserName.UserName.

Example:Example:

<basicHttpBinding><basicHttpBinding>

    <binding name="Binding1"><binding name="Binding1">

          <security mode="TransportWithMessageCredential"><security mode="TransportWithMessageCredential">

                <message clientCredentialType="UserName" /><message clientCredentialType="UserName" />

          </security></security>

    </binding></binding>

</basicHttpBinding></basicHttpBinding>

Page 67: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Deployment in Federated EnvironmentDeployment in Federated EnvironmentWCF Service client obtains a security token from Security Token Service (STS) WCF Service client obtains a security token from Security Token Service (STS)

which is trusted by WCF Servicewhich is trusted by WCF Service

WCF Service should be configured for WSFederatedHttpBindingWCF Service should be configured for WSFederatedHttpBinding

The security token also contains the address of the endpoint to retrieve The security token also contains the address of the endpoint to retrieve

metadata of STSmetadata of STS

the certificate used by STS for signing the security token should be added to the certificate used by STS for signing the security token should be added to the list of known certificates in the service credential section.the list of known certificates in the service credential section.

Page 68: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

<bindings><bindings>  <wsFederationHttpBinding><wsFederationHttpBinding>    <binding name="Binding1"><binding name="Binding1">        <security mode ="Message"><security mode ="Message">                        <message issuedKeyType ="SymmetricKey" issuedTokenType ="http://docs.oasis-open.org/wss/oasis-<message issuedKeyType ="SymmetricKey" issuedTokenType ="http://docs.oasis-open.org/wss/oasis-

wss-saml-token-profile-1.1#SAMLV1.1" >wss-saml-token-profile-1.1#SAMLV1.1" >                            <issuerMetadata address ="http://localhost:8888/sts/mex" ><issuerMetadata address ="http://localhost:8888/sts/mex" >                                <identity><identity>                                    <certificateReference storeLocation ="CurrentUser" <certificateReference storeLocation ="CurrentUser"                                                                                 storeName="TrustedPeople" storeName="TrustedPeople"                                                                                 x509FindType ="FindBySubjectDistinguishedName" x509FindType ="FindBySubjectDistinguishedName"                                                                                 findValue ="CN=STS" />findValue ="CN=STS" />                                </identity></identity>                            </issuerMetadata></issuerMetadata>                        </message></message>                    </security></security>    </binding></binding>  </wsFederationHttpBinding></wsFederationHttpBinding></bindings></bindings><behaviors><behaviors>      <serviceBehaviors><serviceBehaviors>            <behavior name ="ServiceBehaviour" ><behavior name ="ServiceBehaviour" >                    <serviceCredentials><serviceCredentials>                        <issuedTokenAuthentication><issuedTokenAuthentication>                            <knownCertificates><knownCertificates>                                <add storeLocation ="LocalMachine"<add storeLocation ="LocalMachine"                                          storeName="TrustedPeople"storeName="TrustedPeople"                                          x509FindType="FindBySubjectDistinguishedName"x509FindType="FindBySubjectDistinguishedName"                                          findValue="CN=STS" />findValue="CN=STS" />                            </knownCertificates></knownCertificates>                        </issuedTokenAuthentication></issuedTokenAuthentication>                        <serviceCertificate storeLocation ="LocalMachine"<serviceCertificate storeLocation ="LocalMachine"                                                                storeName ="My"storeName ="My"                                                                x509FindType ="FindBySubjectDistinguishedName"x509FindType ="FindBySubjectDistinguishedName"                                                                findValue ="CN=localhost"/>findValue ="CN=localhost"/>                    </serviceCredentials></serviceCredentials>            </behavior></behavior>      </serviceBehaviors></serviceBehaviors></behaviors></behaviors>

Page 69: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind

Assignment For All Assignment For All

Create a WCF service to convert Create a WCF service to convert

Fahrenheit to Celsius and vice versa and Fahrenheit to Celsius and vice versa and to be hosted in IISto be hosted in IIS

If done: mail it on If done: mail it on [email protected][email protected]

Page 70: Wcf architecture overview

Tuesday, April 11, 2023Tuesday, April 11, 2023 ArbindArbind