KEMBAR78
Wcf architecture overview | PPT
WCF Architecture Overview




Sunday, December 16, 2012   Arbind
WCF Service
A service exposes endpoints

(Endpoint: a port to communicate with outside world)




Sunday, December 16, 2012
                       Arbind
A Client
Exchanges messages with one or more Endpoints.

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




Sunday, December 16, 2012
                       Arbind
Endpoint: Has
        1. An Address
        2. A Binding
        3. A Contract




Sunday, December 16, 2012
                       Arbind
Address:

A network location where the Endpoint resides.

Represented by an EndpointAddress Class

EndpointAddress is a URI, a collection of AddressHeader and identity




Sunday, December 16, 2012
                       Arbind
Bindings: Has
           1. A name
           2. A namespace
               3. A collection of binding elements




Sunday, December 16, 2012
                       Arbind
Collection of binding elements:

Each binding elements describe how to communicate with the end point

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

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

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




Sunday, December 16, 2012
                       Arbind
Contracts:

Refers to the collection of operations which specify what endpoint will
   communicate to out side world




Sunday, December 16, 2012
                       Arbind
ContractDescription        class is used to describe WCF Contracts
  and their operations.

Each Contract Operation have OperationDescriptions and

each operationDescription have MessageDescription




Sunday, December 16, 2012
                       Arbind
Duplex Contract:        Defines two Logical Operations

               1. A set that the Service exposes for the Client to call

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




Sunday, December 16, 2012
                       Arbind
Contract: Has
       1. Name
       2. Namespace
       3. Identity




Sunday, December 16, 2012
                       Arbind
Contract:




Sunday, December 16, 2012
                       Arbind
Behaviors:

Are types which modifies services or client functionalities




Sunday, December 16, 2012
                       Arbind
ServiceBehavior       is a type which implements
  IServiceBehavior and applies to service




Sunday, December 16, 2012
                       Arbind
ChannelBehavior         is a type which implements
  IChannelBehavior and applies to client




Sunday, December 16, 2012
                       Arbind
Service and Channel Descriptions
The ServiceDescription class describes a WCF Service including the
  Endpoints exposed by the Service, the Behaviors applied to the
  Service, and the type (a class) that implements the Service.

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




Sunday, December 16, 2012
                       Arbind
Behavior:




Sunday, December 16, 2012
                       Arbind
ChannelDescription             describes a WCF Client's Channel to a
    specific Endpoint




ServiceDescription can have multiple endpoint but
ChannelDescription have only one endpoint



Sunday, December 16, 2012
                       Arbind
WCF Runtime:

The set of objects responsible for sending and receiving messages




Sunday, December 16, 2012
                       Arbind
Message:

The unit of data exchange between a Client and an Endpoint

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




Sunday, December 16, 2012
                       Arbind
Channels:

Channels are the core abstraction for sending Messages to and
  receiving Messages from an Endpoint.




Sunday, December 16, 2012
                       Arbind
Two Category of channel:

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

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




Sunday, December 16, 2012
                       Arbind
Procedure to define WCF Service
Step1: Defining and Implementing a Contract
using System.ServiceModel;

[ServiceContract]
public interface IMath
{
      [OperationContract]
      int Add(int x, int y);
}

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

public class MathService : IMath
{
      public int Add(int x, int y)
     {
         return x + y;
     }
}




Sunday, December 16, 2012
                       Arbind
Step3: Defining Endpoints and Starting the Service
(endpoint can be defined in code or in config)

In Code:
public class WCFServiceApp
{
     public void DefineEndpointImperatively()
     {
           //create a service host for MathService
           ServiceHost sh = new ServiceHost(typeof(MathService));
           //use the AddEndpoint helper method to
           //create the ServiceEndpoint and add it
           //to the ServiceDescription
           sh.AddServiceEndpoint( typeof(IMath),
           //contract type new WSHttpBinding(),
           //one of the built-in bindings "http://localhost/MathService/Ep1");
           //the endpoint's address
           //create and open the service runtime
           sh.Open();
     }
     public void DefineEndpointInConfig()
     {
           //create a service host for MathService
           ServiceHost sh = new ServiceHost (typeof(MathService));
           //create and open the service runtime
           sh.Open();
     }
}
Sunday, December 16, 2012
                       Arbind
Endpoint in config file:
<!-- configuration file used by above code -->
<configuration
   xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<system.serviceModel>
<services>
<!-- service element references the service type -->
<service type="MathService">
<!-- endpoint element defines the ABC's of the endpoint -->
<endpoint address="http://localhost/MathService/Ep1"
   binding="wsHttpBinding" contract="IMath"/>
</service>
</services>
</system.serviceModel>
</configuration>




 Sunday, December 16, 2012
                        Arbind
Step4:       Sending Messages to the Endpoint
using System.ServiceModel;
//this contract is generated by svcutil.exe
//from the service's metadata
public interface IMath
{
      [OperationContract]
      public int Add(int x, int y)
      {
         return x + y;
      }
}
//this class is generated by svcutil.exe
//from the service's metadata
//generated config is not shown here
public class MathProxy : IMath
{ ... }



Continue……….


Sunday, December 16, 2012
                       Arbind
In the following code first way to send the message to endpoint is like
    SendMessageToEndpoint part. This hides the channel creation which is happening
    behind the scene
Second way (SendMessageToEndpointUsingChannel) does it explicitly.

public class WCFClientApp
{
    public void SendMessageToEndpoint()
    {
         //this uses a proxy class that was
         //created by svcutil.exe from the service's metadata
         MathProxy proxy = new MathProxy();
         int result = proxy.Add(35, 7);
    }
    public void SendMessageToEndpointUsingChannel()
    {
         //this uses ChannelFactory to create the channel
         //you must specify the address, the binding and
         //the contract type (IMath)
         ChannelFactory<IMath> factory=new ChannelFactory<IMath>( new WSHttpBinding(), new
             EndpointAddress("http://localhost/MathService/Ep1"));
         IMath channel=factory.CreateChannel();
         int result=channel.Add(35,7);
         factory.Close();
    }
}

Sunday, December 16, 2012
                       Arbind
Step5:      Defining custom behavior
We need to implement IServiceBehavior for service and IChannelBehavior for
  client

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

ServiceHost sh = new ServiceHost(typeof(MathService));
    sh.AddServiceEndpoint( typeof(IMath), new WSHttpBinding(),
    "http://localhost/MathService/Ep1");
//Add the behavior imperatively
// InspectorBehavior is a custom behavior
InspectorBehavior behavior = new InspectorBehavior();
    sh.Description.Behaviors.Add(behavior);
sh.Open();




 Sunday, December 16, 2012
                        Arbind
Secure Hosting and Deployment of WCF Services

Service host is a execution environment for service code

Service has to be hosted before deployment




Sunday, December 16, 2012
                       Arbind
Why host is required?

   Provide security context for the execution of WCF service
   Providing a mechanism to configure the WCF service
   Providing a mechanism to monitor the statistics and health of WCF
    service
   Provide rapid fail protection and tools for WCF service
    management




Sunday, December 16, 2012
                       Arbind
Type of host
  1. Managed Application / Self Host
  2.   Managed Windows Service
  3.   IIS
  4.   WAS




Sunday, December 16, 2012
                       Arbind
Criteria for Choosing a WCF Service Host

Consider following things before coming to conclusion

A. Target Deployment Platform
B. Protocol to be supported by the service




 Sunday, December 16, 2012
                        Arbind
Example:

If service needed to support HTTP, TCP, MSMQ and Named Pipe and
    platform is Windows longhorn server – IIS 7.0 with WAS should
    be used
If service needed to support HTTP and platform is Windows server
    2003 – IIS 6.0 should be used
if TCP, MSMQ and Named Pipe required to be supported and
    platform is Windows server 2003 - Managed Windows Service can
    be used
If service need to support HTTP, TCP, MSMQ and Named Pipe
    protocols on Windows Vista – IIS 7.0 along with WAS should be
    used
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 Pipe




Sunday, December 16, 2012
                       Arbind
How to select host?

Managed Application / Self Host

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

ServiceHost Class is a member of System.ServiceModel namespace

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




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


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




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




Sunday, December 16, 2012
                       Arbind
The security context in Self Host is the identity under which the
  managed application runs




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




Sunday, December 16, 2012
                       Arbind
Code sample for creating a Service Host in
  managed application

Using(ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService)))
{
  //Open the Service Host to start receiving messages
    serviceHost.Open();
    // The service is now ready to accept requests
    …..
  …..
    // Close the ServiceHost to shutdown the service.
    serviceHost.Close();
}




Sunday, December 16, 2012
                       Arbind
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
   shown below:
<system.serviceModel>
  <services>
   <service
     name="SecureHosting.Samples.CalculatorService"
     behaviorConfiguration="CalculatorServiceBehavior">
    <host>
     <baseAddresses>
      <add baseAddress="http://localhost:9000/SecureHostingSamples/service"/>
     </baseAddresses>
    </host>
    <endpoint address=""
          binding="wsHttpBinding"
          contract="SecureHosting.Samples.ICalculator" />
    <endpoint address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange" />
   </service>
  </services>

  <behaviors>
   <serviceBehaviors>
    <behavior name="CalculatorServiceBehavior">
     <serviceMetadata httpGetEnabled="True"/>
     <serviceDebug includeExceptionDetailInFaults="True" />
    </behavior>
   </serviceBehaviors>
  </behaviors>

 </system.serviceModel>




 Sunday, December 16, 2012
                        Arbind
Base Address and endpoint can also be configured
  programmatically instead of configuring in App.Config file


// Create a ServiceHost for the CalculatorService type.
 using (ServiceHost serviceHost =
   new ServiceHost(typeof(CalculatorService),new
     Uri("http://localhost:9000/SecureHostingSamples/service")))
 {

      //Configure the service with an end point
      serviceHost.AddServiceEndpoint(typeof(ICalculator),
        new WSHttpBinding(), "");
      // Open the ServiceHost to start receiving messages
       serviceHost.Open();
    ….
    ….
    ….

    //Close the service host to shutdown the service
      serviceHost.Close ();
}




Sunday, December 16, 2012
                       Arbind
Managed Window Service
(A Window Service running under managed environment)
Service can be installed using Installutil tool.
The service can be exposed to HTTP, TCP, MSMQ and Named Pipe protocol




Sunday, December 16, 2012
                       Arbind
The window service which host the service inherits from the
  ServiceBase class and also implements contract




Sunday, December 16, 2012
                       Arbind
Windows Service provides the facility to manage the lifecycle of the
  service via the Service Control Manager (SCM) console




Sunday, December 16, 2012
                       Arbind
Windows Service Host does not provide a message based activation




Sunday, December 16, 2012
                       Arbind
Window service leverages the OnStart event to create service host
  and host closes on OnStop event.




Sunday, December 16, 2012
                       Arbind
Security context can be configured using Installer Class with the help
  of ServiceProcessInstaller.




Sunday, December 16, 2012
                       Arbind
Sample Code to create Managed Window Service
public class CalculatorService : ServiceBase, ICalculator
{
   public ServiceHost serviceHost = null;

    public static void Main()
    {
       ServiceBase.Run(new CalculatorService());
    }

    public CalculatorService()
    {
       ServiceName = "WCFWindowsCalculatorService";
    }

    //Start the Windows service.
    protected override void OnStart(string[] args)
    {
       if (serviceHost != null)
       {
            serviceHost.Close();
       }
        // Create a ServiceHost for the Service
        serviceHost = new ServiceHost(typeof(CalculatorService));

        // Start Listening for the Messages
        serviceHost.Open();
    }

    //Stop the Windows Service
    protected override void OnStop()
    {
       if (serviceHost != null)
       {
          serviceHost.Close();
          serviceHost = null;
       }
    }
}

 Sunday, December 16, 2012
                        Arbind
IIS
Allows the Services to be hosted in the App Domains inside the ASP.NET
    worker process
Supported IIS: 5.1, 6.0, 7.0 8.0(BETA)
(Only Http and Https can be handled)




Sunday, December 16, 2012
                       Arbind
IIS handles the service request in the same way as it handles web
   request



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




Sunday, December 16, 2012
                       Arbind
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 runs.

                     (Knowledge Sharing)
        WHAT WILL BE THE SECURITY TO BE IMPLEMENTED?




Sunday, December 16, 2012
                       Arbind
Hosting a service in IIS requires .SVC file to be created

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

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




Sunday, December 16, 2012
                       Arbind
The configuration for the service endpoints has to be defined in the
  Web.Config

The .SVC file should contain code like:

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




Sunday, December 16, 2012
                       Arbind
Web.Config for IIS Host:

<system.serviceModel>
  <services>
   <service name="SecureHosting.Samples.CalculatorService"
          behaviorConfiguration="CalculatorServiceBehavior">
     <!-- This endpoint is exposed at the base address provided by host:
   http://localhost/securehostingsamples/service.svc -->
     <endpoint address=""
            binding="wsHttpBinding"
            contract="SecureHosting.Samples.ICalculator" />
     <endpoint address="mex"
            binding="mexHttpBinding"
            contract="IMetadataExchange" />
   </service>
  </services>

  <!--For debugging purposes set the includeExceptionDetailInFaults attribute to true--
   >
  <behaviors>
   <serviceBehaviors>
     <behavior name="CalculatorServiceBehavior">
      <serviceMetadata httpGetEnabled="True"/>
      <serviceDebug includeExceptionDetailInFaults="True" />
     </behavior>
   </serviceBehaviors>
  </behaviors>

 </system.serviceModel>
Sunday, December 16, 2012
                       Arbind
WAS (Windows Activation Service)

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

Available with Windows Vista and Windows Longhorn Server

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




Sunday, December 16, 2012
                       Arbind
Note:
1. web sites need to be configured via the APPCMD utility to support
   non HTTP protocols

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




Sunday, December 16, 2012
                       Arbind
Command to run:

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

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

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




Sunday, December 16, 2012
                       Arbind
After running the command APPCMD updates configuration file for WAS
   ApplicationHost.Config
<system.applicationHost>
 <sites>
  <site name="Default Web Site" id="1">
    <bindings>
     <binding protocol="http"
               bindingInformation="*:80:" />
     <binding protocol="net.pipe"
               bindingInformation="*" />
     <binding protocol="net.tcp"
               bindingInformation="808:*" />
     <binding protocol="net.msmq"
               bindingInformation="*" />
    </bindings>
  </site>
 </sites>
</system.applicationHost>




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

 %windir%system32inetsrvappcmd.exe set app "Default Web
  Site/securehostingsamples" /enabledProtocols:http,net.tcp




Sunday, December 16, 2012
                       Arbind
Selecting Binding:
Criteria to select Bindings:
1. Consider the deployment environment whether it is for Internet, Intranet,
    Federated Environment, Windows only or a Heterogeneous Environment
2. Security to be implemented
3. Performance Issues




Sunday, December 16, 2012
                       Arbind
A WCF service can be assigned:
  1. Transport level security,
  2. Message level security or
  3. A combination of transport and message level security.




Sunday, December 16, 2012
                       Arbind
A service can be defined with an authentication mode of
    1. None,
    2. Username,
    3. Windows,
    4. Certificates and
    5. IssuedToken.

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




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

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

ClientCredentialType is set to Windows to enable Windows Authentication

Code Sample:

<bindings>
 <netTcpBinding>
  <binding name="Binding1">
      <security mode="Transport" />
        <transport
   clientCredentialType="Windows" protectionLevel="EncryptAndSign"/>
      </security>
  </binding>
 </netTcpBinding>
</bindings>




Sunday, December 16, 2012
                       Arbind
Interoperability with web services

The WCF service can be configured to use BasicHttpBinding with transport
   level security.
HTTP/GET metadata should be enabled for the service in the service behavior
   section.




Sunday, December 16, 2012
                       Arbind
Deploying a WCF Service over Internet or in a Heterogeneous Environment
(needs to potentially interact with the clients on non-windows platforms)

--BasicHttpBinding or WSHttpBinding can be used depending upon the level of
    conformance required with the commonly used security standards
If interoperability is required with web service only BasicHttpBinding should be
    used.




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

Example:

<basicHttpBinding>
 <binding name="Binding1">
   <security mode="TransportWithMessageCredential">
     <message clientCredentialType="UserName" />
   </security>
 </binding>
</basicHttpBinding>




Sunday, December 16, 2012
                       Arbind
Deployment in Federated Environment
WCF Service client obtains a security token from Security Token Service (STS)
  which is trusted by WCF Service

WCF Service should be configured for WSFederatedHttpBinding

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


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




Sunday, December 16, 2012
                       Arbind
<bindings>
<wsFederationHttpBinding>
 <binding name="Binding1">
  <security mode ="Message">
       <message issuedKeyType ="SymmetricKey" issuedTokenType ="http://docs.oasis-open.org/wss/oasis-
    wss-saml-token-profile-1.1#SAMLV1.1" >
        <issuerMetadata address ="http://localhost:8888/sts/mex" >
         <identity>
          <certificateReference storeLocation ="CurrentUser"
                        storeName="TrustedPeople"
                        x509FindType ="FindBySubjectDistinguishedName"
                        findValue ="CN=STS" />
         </identity>
        </issuerMetadata>
       </message>
     </security>
 </binding>
</wsFederationHttpBinding>
</bindings>
<behaviors>
 <serviceBehaviors>
   <behavior name ="ServiceBehaviour" >
     <serviceCredentials>
       <issuedTokenAuthentication>
        <knownCertificates>
         <add storeLocation ="LocalMachine"
            storeName="TrustedPeople"
            x509FindType="FindBySubjectDistinguishedName"
            findValue="CN=STS" />
        </knownCertificates>
       </issuedTokenAuthentication>
       <serviceCertificate storeLocation ="LocalMachine"
                   storeName ="My"
                   x509FindType ="FindBySubjectDistinguishedName"
                   findValue ="CN=localhost"/>
     </serviceCredentials>
   </behavior>
 </serviceBehaviors>
</behaviors>


Sunday, December 16, 2012
                       Arbind
Assignment For All

   Create a WCF service to convert
Fahrenheit to Celsius and vice versa and
            to be hosted in IIS

                    If done: mail it on
              arbindkumar_tiwari@satyam.com




Sunday, December 16, 2012
                       Arbind
Sunday, December 16, 2012
                       Arbind

Wcf architecture overview

  • 1.
    WCF Architecture Overview Sunday,December 16, 2012 Arbind
  • 2.
    WCF Service A serviceexposes endpoints (Endpoint: a port to communicate with outside world) Sunday, December 16, 2012 Arbind
  • 3.
    A Client Exchanges messageswith one or more Endpoints. May also expose an Endpoint to receive Messages from a Service in a duplex message exchange pattern. Sunday, December 16, 2012 Arbind
  • 4.
    Endpoint: Has 1. An Address 2. A Binding 3. A Contract Sunday, December 16, 2012 Arbind
  • 5.
    Address: A network locationwhere the Endpoint resides. Represented by an EndpointAddress Class EndpointAddress is a URI, a collection of AddressHeader and identity Sunday, December 16, 2012 Arbind
  • 6.
    Bindings: Has 1. A name 2. A namespace 3. A collection of binding elements Sunday, December 16, 2012 Arbind
  • 7.
    Collection of bindingelements: Each binding elements describe how to communicate with the end point 1. TcpTransportBindingElement indicates that the Endpoint will communicate with the world using TCP as the transport protocol. 2. ReliableSessionBindingElement indicates that the Endpoint uses reliable messaging to provide message delivery assurances. 3. SecurityBindingElement indicates that the Endpoint uses SOAP message security. Sunday, December 16, 2012 Arbind
  • 8.
    Contracts: Refers to thecollection of operations which specify what endpoint will communicate to out side world Sunday, December 16, 2012 Arbind
  • 9.
    ContractDescription class is used to describe WCF Contracts and their operations. Each Contract Operation have OperationDescriptions and each operationDescription have MessageDescription Sunday, December 16, 2012 Arbind
  • 10.
    Duplex Contract: Defines two Logical Operations 1. A set that the Service exposes for the Client to call 2. A set that the Client exposes for the Service to call Sunday, December 16, 2012 Arbind
  • 11.
    Contract: Has 1. Name 2. Namespace 3. Identity Sunday, December 16, 2012 Arbind
  • 12.
  • 13.
    Behaviors: Are types whichmodifies services or client functionalities Sunday, December 16, 2012 Arbind
  • 14.
    ServiceBehavior is a type which implements IServiceBehavior and applies to service Sunday, December 16, 2012 Arbind
  • 15.
    ChannelBehavior is a type which implements IChannelBehavior and applies to client Sunday, December 16, 2012 Arbind
  • 16.
    Service and ChannelDescriptions The ServiceDescription class describes a WCF Service including the Endpoints exposed by the Service, the Behaviors applied to the Service, and the type (a class) that implements the Service. ServiceDescription is used to create metadata, code/config, and channels. Sunday, December 16, 2012 Arbind
  • 17.
  • 18.
    ChannelDescription describes a WCF Client's Channel to a specific Endpoint ServiceDescription can have multiple endpoint but ChannelDescription have only one endpoint Sunday, December 16, 2012 Arbind
  • 19.
    WCF Runtime: The setof objects responsible for sending and receiving messages Sunday, December 16, 2012 Arbind
  • 20.
    Message: The unit ofdata exchange between a Client and an Endpoint A message should be of SOAP message type and can be serialized using the WCF binary format, text XML, or any other custom format. Sunday, December 16, 2012 Arbind
  • 21.
    Channels: Channels are thecore abstraction for sending Messages to and receiving Messages from an Endpoint. Sunday, December 16, 2012 Arbind
  • 22.
    Two Category ofchannel: 1. Transport Channels handle sending or receiving opaque octet streams using some form of transport protocol such as TCP, UDP, or MSMQ. 2. Protocol Channels, implement a SOAP-based protocol by processing and possibly modifying messages. Sunday, December 16, 2012 Arbind
  • 23.
    Procedure to defineWCF Service Step1: Defining and Implementing a Contract using System.ServiceModel; [ServiceContract] public interface IMath { [OperationContract] int Add(int x, int y); } Step2: Define a service class This contract (interface IMath) is implemented to a class which becomes a service class public class MathService : IMath { public int Add(int x, int y) { return x + y; } } Sunday, December 16, 2012 Arbind
  • 24.
    Step3: Defining Endpointsand Starting the Service (endpoint can be defined in code or in config) In Code: public class WCFServiceApp { public void DefineEndpointImperatively() { //create a service host for MathService ServiceHost sh = new ServiceHost(typeof(MathService)); //use the AddEndpoint helper method to //create the ServiceEndpoint and add it //to the ServiceDescription sh.AddServiceEndpoint( typeof(IMath), //contract type new WSHttpBinding(), //one of the built-in bindings "http://localhost/MathService/Ep1"); //the endpoint's address //create and open the service runtime sh.Open(); } public void DefineEndpointInConfig() { //create a service host for MathService ServiceHost sh = new ServiceHost (typeof(MathService)); //create and open the service runtime sh.Open(); } } Sunday, December 16, 2012 Arbind
  • 25.
    Endpoint in configfile: <!-- configuration file used by above code --> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.serviceModel> <services> <!-- service element references the service type --> <service type="MathService"> <!-- endpoint element defines the ABC's of the endpoint --> <endpoint address="http://localhost/MathService/Ep1" binding="wsHttpBinding" contract="IMath"/> </service> </services> </system.serviceModel> </configuration> Sunday, December 16, 2012 Arbind
  • 26.
    Step4: Sending Messages to the Endpoint using System.ServiceModel; //this contract is generated by svcutil.exe //from the service's metadata public interface IMath { [OperationContract] public int Add(int x, int y) { return x + y; } } //this class is generated by svcutil.exe //from the service's metadata //generated config is not shown here public class MathProxy : IMath { ... } Continue………. Sunday, December 16, 2012 Arbind
  • 27.
    In the followingcode first way to send the message to endpoint is like SendMessageToEndpoint part. This hides the channel creation which is happening behind the scene Second way (SendMessageToEndpointUsingChannel) does it explicitly. public class WCFClientApp { public void SendMessageToEndpoint() { //this uses a proxy class that was //created by svcutil.exe from the service's metadata MathProxy proxy = new MathProxy(); int result = proxy.Add(35, 7); } public void SendMessageToEndpointUsingChannel() { //this uses ChannelFactory to create the channel //you must specify the address, the binding and //the contract type (IMath) ChannelFactory<IMath> factory=new ChannelFactory<IMath>( new WSHttpBinding(), new EndpointAddress("http://localhost/MathService/Ep1")); IMath channel=factory.CreateChannel(); int result=channel.Add(35,7); factory.Close(); } } Sunday, December 16, 2012 Arbind
  • 28.
    Step5: Defining custom behavior We need to implement IServiceBehavior for service and IChannelBehavior for client All behaviors can be applied imperatively by adding an instance of the behavior to the ServiceDescription (or the ChannelDescription on the client side). ServiceHost sh = new ServiceHost(typeof(MathService)); sh.AddServiceEndpoint( typeof(IMath), new WSHttpBinding(), "http://localhost/MathService/Ep1"); //Add the behavior imperatively // InspectorBehavior is a custom behavior InspectorBehavior behavior = new InspectorBehavior(); sh.Description.Behaviors.Add(behavior); sh.Open(); Sunday, December 16, 2012 Arbind
  • 29.
    Secure Hosting andDeployment of WCF Services Service host is a execution environment for service code Service has to be hosted before deployment Sunday, December 16, 2012 Arbind
  • 30.
    Why host isrequired?  Provide security context for the execution of WCF service  Providing a mechanism to configure the WCF service  Providing a mechanism to monitor the statistics and health of WCF service  Provide rapid fail protection and tools for WCF service management Sunday, December 16, 2012 Arbind
  • 31.
    Type of host 1. Managed Application / Self Host 2. Managed Windows Service 3. IIS 4. WAS Sunday, December 16, 2012 Arbind
  • 32.
    Criteria for Choosinga WCF Service Host Consider following things before coming to conclusion A. Target Deployment Platform B. Protocol to be supported by the service Sunday, December 16, 2012 Arbind
  • 33.
    Example: If service neededto support HTTP, TCP, MSMQ and Named Pipe and platform is Windows longhorn server – IIS 7.0 with WAS should be used If service needed to support HTTP and platform is Windows server 2003 – IIS 6.0 should be used if TCP, MSMQ and Named Pipe required to be supported and platform is Windows server 2003 - Managed Windows Service can be used If service need to support HTTP, TCP, MSMQ and Named Pipe protocols on Windows Vista – IIS 7.0 along with WAS should be used 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 Pipe Sunday, December 16, 2012 Arbind
  • 34.
    How to selecthost? Managed Application / Self Host Any .NET managed application can host a WCF service by creating an instance of ServiceHost Class ServiceHost Class is a member of System.ServiceModel namespace (Hosting a Service in managed application is also called Self Hosting) Sunday, December 16, 2012 Arbind
  • 35.
    Point to note: Self host does not provide features like message based activation, mechanism to monitor service health or service host resources or recycling of the service host process upon detection of error conditions. And so: This is useful in development environment but not in production environment Sunday, December 16, 2012 Arbind
  • 36.
    In Self Hosting,the Service Host has to be instantiated at the time of the managed application startup and closed before the managed application shutdown. Sunday, December 16, 2012 Arbind
  • 37.
    The security contextin Self Host is the identity under which the managed application runs Sunday, December 16, 2012 Arbind
  • 38.
    A WCF Servicehosted in a managed application can be exposed over TCP, HTTP, HTTPS, Named Pipe and MSMQ protocols. Sunday, December 16, 2012 Arbind
  • 39.
    Code sample forcreating a Service Host in managed application Using(ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService))) { //Open the Service Host to start receiving messages serviceHost.Open(); // The service is now ready to accept requests ….. ….. // Close the ServiceHost to shutdown the service. serviceHost.Close(); } Sunday, December 16, 2012 Arbind
  • 40.
    The base addressand 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 shown below: <system.serviceModel> <services> <service name="SecureHosting.Samples.CalculatorService" behaviorConfiguration="CalculatorServiceBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:9000/SecureHostingSamples/service"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="SecureHosting.Samples.ICalculator" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="CalculatorServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> Sunday, December 16, 2012 Arbind
  • 41.
    Base Address andendpoint can also be configured programmatically instead of configuring in App.Config file // Create a ServiceHost for the CalculatorService type. using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService),new Uri("http://localhost:9000/SecureHostingSamples/service"))) { //Configure the service with an end point serviceHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), ""); // Open the ServiceHost to start receiving messages serviceHost.Open(); …. …. …. //Close the service host to shutdown the service serviceHost.Close (); } Sunday, December 16, 2012 Arbind
  • 42.
    Managed Window Service (AWindow Service running under managed environment) Service can be installed using Installutil tool. The service can be exposed to HTTP, TCP, MSMQ and Named Pipe protocol Sunday, December 16, 2012 Arbind
  • 43.
    The window servicewhich host the service inherits from the ServiceBase class and also implements contract Sunday, December 16, 2012 Arbind
  • 44.
    Windows Service providesthe facility to manage the lifecycle of the service via the Service Control Manager (SCM) console Sunday, December 16, 2012 Arbind
  • 45.
    Windows Service Hostdoes not provide a message based activation Sunday, December 16, 2012 Arbind
  • 46.
    Window service leveragesthe OnStart event to create service host and host closes on OnStop event. Sunday, December 16, 2012 Arbind
  • 47.
    Security context canbe configured using Installer Class with the help of ServiceProcessInstaller. Sunday, December 16, 2012 Arbind
  • 48.
    Sample Code tocreate Managed Window Service public class CalculatorService : ServiceBase, ICalculator { public ServiceHost serviceHost = null; public static void Main() { ServiceBase.Run(new CalculatorService()); } public CalculatorService() { ServiceName = "WCFWindowsCalculatorService"; } //Start the Windows service. protected override void OnStart(string[] args) { if (serviceHost != null) { serviceHost.Close(); } // Create a ServiceHost for the Service serviceHost = new ServiceHost(typeof(CalculatorService)); // Start Listening for the Messages serviceHost.Open(); } //Stop the Windows Service protected override void OnStop() { if (serviceHost != null) { serviceHost.Close(); serviceHost = null; } } } Sunday, December 16, 2012 Arbind
  • 49.
    IIS Allows the Servicesto be hosted in the App Domains inside the ASP.NET worker process Supported IIS: 5.1, 6.0, 7.0 8.0(BETA) (Only Http and Https can be handled) Sunday, December 16, 2012 Arbind
  • 50.
    IIS handles theservice request in the same way as it handles web request Supports message based activation and service instance is created only after receiving the first message. Sunday, December 16, 2012 Arbind
  • 51.
    The security contextfor the WCF Service hosted inside the ASP.NET worker process is provided by the service account under which the worker process runs. (Knowledge Sharing) WHAT WILL BE THE SECURITY TO BE IMPLEMENTED? Sunday, December 16, 2012 Arbind
  • 52.
    Hosting a servicein IIS requires .SVC file to be created If required a Custom Service Host we can create it using System.ServiceModel.Activation.ServiceHostFactory Class (Virtual applications are created and DLLs and sources are deployed to the physical path associated with the virtual application) Sunday, December 16, 2012 Arbind
  • 53.
    The configuration forthe service endpoints has to be defined in the Web.Config The .SVC file should contain code like: <%@ServiceHost language=c# Debug="true" Service=" SecureHosting.Samples.CalculatorService" %> Sunday, December 16, 2012 Arbind
  • 54.
    Web.Config for IISHost: <system.serviceModel> <services> <service name="SecureHosting.Samples.CalculatorService" behaviorConfiguration="CalculatorServiceBehavior"> <!-- This endpoint is exposed at the base address provided by host: http://localhost/securehostingsamples/service.svc --> <endpoint address="" binding="wsHttpBinding" contract="SecureHosting.Samples.ICalculator" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <!--For debugging purposes set the includeExceptionDetailInFaults attribute to true-- > <behaviors> <serviceBehaviors> <behavior name="CalculatorServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> Sunday, December 16, 2012 Arbind
  • 55.
    WAS (Windows ActivationService) WAS enables IIS 7.0 to leverage message based activation for protocols such as TCP, MSMQ and Named Pipes in addition to the HTTP protocol Available with Windows Vista and Windows Longhorn Server Service deployment process for IIS 7.0/WAS is same as discussed earlier for IIS host Sunday, December 16, 2012 Arbind
  • 56.
    Note: 1. web sitesneed to be configured via the APPCMD utility to support non HTTP protocols 2. To do this command shell must be started in “Run as Administrator” mode Sunday, December 16, 2012 Arbind
  • 57.
    Command to run: %windir%system32inetsrvappcmd.exeset site "Default Web Site" -+bindings.[protocol='net.tcp',bindingInformation='808:*'] FOR TCP %windir%system32inetsrvappcmd.exe set site "Default Web Site" -+bindings.[protocol='net.msmq',bindingInformation='*'] FOR MSMQ %windir%system32inetsrvappcmd.exe set site "Default Web Site" -+bindings.[protocol='net.pipe',bindingInformation='*'] FOR NAMED PIPE Sunday, December 16, 2012 Arbind
  • 58.
    After running thecommand APPCMD updates configuration file for WAS ApplicationHost.Config <system.applicationHost> <sites> <site name="Default Web Site" id="1"> <bindings> <binding protocol="http" bindingInformation="*:80:" /> <binding protocol="net.pipe" bindingInformation="*" /> <binding protocol="net.tcp" bindingInformation="808:*" /> <binding protocol="net.msmq" bindingInformation="*" /> </bindings> </site> </sites> </system.applicationHost> Sunday, December 16, 2012 Arbind
  • 59.
    To enable theTCP protocol (in addition to the HTTP protocol) for the “SecureHostingSamples” application, the following command should be run from an administrator shell: %windir%system32inetsrvappcmd.exe set app "Default Web Site/securehostingsamples" /enabledProtocols:http,net.tcp Sunday, December 16, 2012 Arbind
  • 60.
    Selecting Binding: Criteria toselect Bindings: 1. Consider the deployment environment whether it is for Internet, Intranet, Federated Environment, Windows only or a Heterogeneous Environment 2. Security to be implemented 3. Performance Issues Sunday, December 16, 2012 Arbind
  • 61.
    A WCF servicecan be assigned: 1. Transport level security, 2. Message level security or 3. A combination of transport and message level security. Sunday, December 16, 2012 Arbind
  • 62.
    A service canbe defined with an authentication mode of 1. None, 2. Username, 3. Windows, 4. Certificates and 5. IssuedToken. Authentication process between the client and the service includes the authentication of service to the client as well as the authentication of the client to the service. Sunday, December 16, 2012 Arbind
  • 63.
    Deploying a WCFService over Windows Only Intranet In Windows only Intranet, if all the service clients are WCF clients, the service can be deployed using NetTCPBinding and transport level security to achieve maximum performance. (NetTCPBinding by default uses transport level security along with TCP channel and binary message encoding) ClientCredentialType is set to Windows to enable Windows Authentication Code Sample: <bindings> <netTcpBinding> <binding name="Binding1"> <security mode="Transport" /> <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign"/> </security> </binding> </netTcpBinding> </bindings> Sunday, December 16, 2012 Arbind
  • 64.
    Interoperability with webservices The WCF service can be configured to use BasicHttpBinding with transport level security. HTTP/GET metadata should be enabled for the service in the service behavior section. Sunday, December 16, 2012 Arbind
  • 65.
    Deploying a WCFService over Internet or in a Heterogeneous Environment (needs to potentially interact with the clients on non-windows platforms) --BasicHttpBinding or WSHttpBinding can be used depending upon the level of conformance required with the commonly used security standards If interoperability is required with web service only BasicHttpBinding should be used. Sunday, December 16, 2012 Arbind
  • 66.
    To support SOAPMessage Security UserName Token Profile version 1.0, the WCF service should be configured with BasicHttpBinding with security mode of TransportWithMessageCredential and client credential type of UserName. Example: <basicHttpBinding> <binding name="Binding1"> <security mode="TransportWithMessageCredential"> <message clientCredentialType="UserName" /> </security> </binding> </basicHttpBinding> Sunday, December 16, 2012 Arbind
  • 67.
    Deployment in FederatedEnvironment WCF Service client obtains a security token from Security Token Service (STS) which is trusted by WCF Service WCF Service should be configured for WSFederatedHttpBinding The security token also contains the address of the endpoint to retrieve metadata of STS the certificate used by STS for signing the security token should be added to the list of known certificates in the service credential section. Sunday, December 16, 2012 Arbind
  • 68.
    <bindings> <wsFederationHttpBinding> <binding name="Binding1"> <security mode ="Message"> <message issuedKeyType ="SymmetricKey" issuedTokenType ="http://docs.oasis-open.org/wss/oasis- wss-saml-token-profile-1.1#SAMLV1.1" > <issuerMetadata address ="http://localhost:8888/sts/mex" > <identity> <certificateReference storeLocation ="CurrentUser" storeName="TrustedPeople" x509FindType ="FindBySubjectDistinguishedName" findValue ="CN=STS" /> </identity> </issuerMetadata> </message> </security> </binding> </wsFederationHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name ="ServiceBehaviour" > <serviceCredentials> <issuedTokenAuthentication> <knownCertificates> <add storeLocation ="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectDistinguishedName" findValue="CN=STS" /> </knownCertificates> </issuedTokenAuthentication> <serviceCertificate storeLocation ="LocalMachine" storeName ="My" x509FindType ="FindBySubjectDistinguishedName" findValue ="CN=localhost"/> </serviceCredentials> </behavior> </serviceBehaviors> </behaviors> Sunday, December 16, 2012 Arbind
  • 69.
    Assignment For All Create a WCF service to convert Fahrenheit to Celsius and vice versa and to be hosted in IIS If done: mail it on arbindkumar_tiwari@satyam.com Sunday, December 16, 2012 Arbind
  • 70.