Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Monday, September 24, 2012

Fault Contract

Service that we develop might get error in come case. This error should be reported to the client in proper manner. Basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific.
In order to support interoperability and client will also be interested only, what wents wrong? not on how and where cause the error.
By default when we throw any exception from service, it will not reach the client side. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract.
Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error accorded in the service to client. This help as to easy identity the what error has accord. Let us try to understand the concept using sample example.
Step 1: I have created simple calculator service with Add operation which will throw general exception as shown below
//Service interface
[ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        int Add(int num1, int num2);
    }
//Service implementation
public  class SimpleCalculator : ISimpleCalculator
    {
    
        public int Add(int num1, int num2)
        {
            //Do something
            throw new Exception("Error while adding number");
            
        }

    }

Step 2: On client side code. Exceptions are handled using try-Catch block. Even though I have capture the exception when I run the application. I got the message that exceptions are not handled properly.
try
   {
      MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy
       = new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
      Console.WriteLine("Client is running at " + DateTime.Now.ToString());
      Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
      Console.ReadLine();
   }
   catch (Exception ex) 
   {
      Console.WriteLine(ex.Message);
      Console.ReadLine();
   }
Step 3: Now if you want to send exception information form service to client, you have to use FaultException as shown below.
        public int Add(int num1, int num2)
        {
            //Do something
            throw new FaultException("Error while adding number");
            
        }
Step 4: Output window on the client side is show below.
Step 5: You can also create your own Custom type and send the error information to the client using FaultContract. These are the steps to be followed to create the fault contract.
  • Define a type using the data contract and specify the fields you want to return.
  • Decorate the service operation with the FaultContract attribute and specify the type name.
  • Raise the exception from the service by creating an instance and assigning properties of the custom exception.
Step 6: Defining the type using Data Contract
    [DataContract()]
    public class CustomException
    {
        [DataMember()]
        public string Title;
        [DataMember()]
        public string ExceptionMessage;
        [DataMember()]
        public string InnerException;
        [DataMember()]
        public string StackTrace;        
    }
Step 7: Decorate the service operation with the FaultContract
    [ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        [FaultContract(typeof(CustomException))]
        int Add(int num1, int num2);
    }
Step 8: Raise the exception from the service
        public int Add(int num1, int num2)
        {
            //Do something
            CustomException ex = new CustomException();
            ex.Title = "Error Funtion:Add()";
            ex.ExceptionMessage = "Error occur while doing add function.";
            ex.InnerException = "Inner exception message from serice";
            ex.StackTrace = "Stack Trace message from service.";
            throw new FaultException(ex,"Reason: Testing the Fault contract") ;
            
        }
Step 9: On client side, you can capture the service exception and process the information, as shown below.
   try
   {
      MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy 
      = new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
       Console.WriteLine("Client is running at " + DateTime.Now.ToString());
       Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
       Console.ReadLine();
    }
    catch (FaultException<MyCalculatorService.CustomException> ex)
     {
        //Process the Exception
     }

Message Contract Properties

ProtectionLevel

You can mention the MessageHeader or MessageBodyMember to be signed or Encrypted using ProtectionLevel property.
Example
 
using System.Net.Security;

    [MessageContract]
    public class EmployeeDetails
    {
        [MessageHeader(ProtectionLevel=ProtectionLevel.None)]
        public string EmpID;
        [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign )]
        public string Name;
        [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign )]
        public string Designation;
        [MessageBodyMember(ProtectionLevel=ProtectionLevel.EncryptAndSign)]
        public int Salary;

    }
In the above type definition, we have made the different protection level for body. But the protection level of the body is determind by the highest ProtectionLevel property. By default if you are not specifying the protection level it takes 'EncryptAndSign'. So it good if you specify minimum ProtectionLevel required.

Name and Namespace:

SOAP representation of the message element can be change by mentioning Name and Namespace property of the Header and Body member. By default namespace is the same as the namespace of the service contract that the message is participating. In the below example, I have mention the Name property to the EmpID and Name.
 
[MessageContract]
    public class EmployeeDetails
    {
        [MessageHeader(Name="ID")]
        public string EmpID;
        [MessageBodyMember(Name="EmployeeName")]
        public string Name;
        [MessageBodyMember()]
        public string Designation;
        [MessageBodyMember()]
        public int Salary;

    }
When SOAP message representation, its name is changed to ID and EmployeeName.
 
<EmployeeDetails>
  <ID>45634</ID>
  <EmployeeName>Sam</EmployeeName>
  <Designation>Software Engineer</Designation>
  <Salary>25000</Salary>
</EmployeeDetails>

Order

The order of the body elements are alpehabetical by default. But you can control the order, usiing Order property in the MessageBody attribute.
 
[MessageContract]
    public class EmployeeDetails
    {
        [MessageHeader()]
        public string EmpID;
        [MessageBodyMember(Order=2)]
        public string Name;
        [MessageBodyMember(Order=3)]
        public string Designation;
        [MessageBodyMember(Order=1)]
        public int Salary;

    }

MessageHeaderArray Attribute

Consider the Message contract type definition as shown below.
 
[MessageContract]
    public class Department
    {
        [MessageHeader]
        public string DepartmentID;
        [MessageHeader]
        public string DepartmentName;
        [MessageHeader]
        public Employees Employee();

    }
In this we are having array of Employee type as message header. When this converted to SOAP Header it looks as shown below.
<Department>
  <DepartmentID>PRO1243</DepartmentID>
  <DepartmentName>Production</DepartmentName>
  <Employees>
    <Employee>Sam</Employee>
    <Employee>Ram</Employee>
    <Employee>Raja</Employee>
  </Employees>
</Department>
Suppose you want to show the all employee detail in same level. We can use MessageHeaderArray attribute which will serialize the array element independently. If you use the MessageHeaderArray attribute of Employees, SOAP message will look as shown below.
<Department>
  <DepartmentID>PRO1243</DepartmentID>
  <DepartmentName>Production</DepartmentName>
  <Employee>Sam</Employee>
  <Employee>Ram</Employee>
  <Employee>Raja</Employee>
</Department>
Note: MessageHeaderArray Attribute is applicable only for Array, not for collection.

Message Contract

Message

Message is the packet of data which contains important information. WCF uses these messages to transfer information from Source to destination.
WCF uses SOAP(Simple Object Access Protocol) Message format for communication. SOAP message contain Envelope, Header and Body.SOAP envelope contails name, namespace,header and body element. SOAP Hear contain important information which are not directly related to message. SOAP body contains information which is used by the target.
Diagram Soap envelope

Message Pattern

It describes how the programs will exchange message each other. There are three way of communication between source and destination
  1. Simplex - It is one way communication. Source will send message to target, but target will not respond to the message.
  2. Request/Replay - It is two way communications, when source send message to the target, it will resend response message to the source. But at a time only one can send a message
  3. Duplex - It is two way communication, both source and target can send and receive message simultaniouly.

What is Message contract?

As I said earlier, WCF uses SOAP message for communication. Most of the time developer will concentrate more on developing the DataContract, Serializing the data, etc. WCF will automatically take care of message. On Some critical issue, developer will also require control over the SOAP message format. In that case WCF provides Message Contract to customize the message as per requirement.
WCF supports either RPC(Remote Procedure Call) or Message style operation model. In the RPC model, you can develop operation with Ref and out parameter. WCF will automatically create the message for operation at run time. In Message style operation WCF allows to customize the message header and define the security for header and body of the message.

Defining Message Contract

Message contract can be applied to type using MessageContract attribute. Custom Header and Body can be included to message using 'MessageHeader' and 'MessageBodyMember'atttribute. Let us see the sample message contract definition.
[MessageContract]
public class EmployeeDetails
{
    [MessageHeader]
    public string EmpID;
    [MessageBodyMember]
    public string Name;
    [MessageBodyMember]
    public string Designation;
    [MessageBodyMember]
    public int Salary;
    [MessageBodyMember]
    public string Location;
}
When I use this EmployeeDeatils type in the service operation as parameter. WCF will add extra header call 'EmpID' to the SOAP envelope. It also add Name, Designation, Salary, Location as extra member to the SOAP Body.

Rules :

You have to follow certain rules while working with Message contract
  1. When using Message contract type as parameter, Only one parameter can be used in servicie Operation
    [OperationContract]
    void SaveEmployeeDetails(EmployeeDetails emp);
    
  2. Service operation either should return Messagecontract type or it should not return any value
    [OperationContract]
    EmployeeDetails GetEmployeeDetails();
    
  3. Service operation will accept and return only message contract type. Other data types are not allowed.
    [OperationContract]
    EmployeeDetails ModifyEmployeeDetails(EmployeeDetails emp);
     
Note: If a type has both Message and Data contract, service operation will accept only message contract.

Data Contract

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.
Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute.
A data contract can be defined as follows:
  • It describes the external format of data passed to and from service operations
  • It defines the structure and types of data exchanged in service messages
  • It maps a CLR type to an XML Schema
  • t defines how data types are serialized and deserialized. Through serialization, you convert an object into a sequence of bytes that can be transmitted over a network. Through deserialization, you reassemble an object from a sequence of bytes that you receive from a calling application.
  • It is a versioning system that allows you to manage changes to structured data
We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract and DataMember attribute.
Create user defined data type called Employee. This data type should be identified for serialization and deserialization by mentioning with [DataContract] and [DataMember] attribute.
 [ServiceContract]
    public interface IEmployeeService
    {
        [OperationContract]
        Employee GetEmployeeDetails(int EmpId);
    }

    [DataContract]
    public class Employee
    {
        private string m_Name;
        private int m_Age;
        private int m_Salary;
        private string m_Designation;
        private string m_Manager;

        [DataMember]
        public string Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }

        [DataMember]
        public int Age
        {
            get { return m_Age; }
            set { m_Age = value; }
        }

        [DataMember]
        public int Salary
        {
            get { return m_Salary; }
            set { m_Salary = value; }
        }

        [DataMember]
        public string Designation
        {
            get { return m_Designation; }
            set { m_Designation = value; }
        }

        [DataMember]
        public string Manager
        {
            get { return m_Manager; }
            set { m_Manager = value; }
        }

    }
Implementation of the service class is shown below. In GetEmployee method we have created the Employee instance and return to the client. Since we have created the data contract for the Employee class, client will aware of this instance whenever he creates proxy for the service.
public class EmployeeService : IEmployeeService
    {
        public Employee GetEmployeeDetails(int empId)
        {
            
            Employee empDetail = new Employee();

            //Do something to get employee details and assign to 'empDetail' properties

            return empDetail;
        }
    }

Client side

On client side we can create the proxy for the service and make use of it. The client side code is shown below.
protected void btnGetDetails_Click(object sender, EventArgs e)
        {
            EmployeeServiceClient objEmployeeClient = new EmployeeServiceClient();
            Employee empDetails;
            empDetails = objEmployeeClient.GetEmployeeDetails(empId);
//Do something on employee details

Service Contract

Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract.
Service Contract can be define using [ServiceContract] and [OperationContract] attribute. [ServiceContract] attribute is similar to the [WebServcie] attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in WebService.
  • It describes the client-callable operations (functions) exposed by the service
  • It maps the interface and methods of your service to a platform-independent description
  • It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern
  • It is analogous to the element in WSDL
To create a service contract you define an interface with related methods representative of a collection of service operations, and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract. Methods in the interface that should be included in the service contract are decorated with the OperationContract Attribute.
[ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        int Add(int num1, int num2);
    }
Once we define Service contract in the interface, we can create implement class for this interface.
public  class SimpleCalculator : ISimpleCalculator
    {
    
        public int Add(int num1, int num2)
        {
            return num1 + num2;
        }

    }
With out creating the interface, we can also directly created the service by placing Contract in the implemented class. But it is not good practice of creating the service
[ServiceContract()]
   public class SimpleCalculator 
   {
       [OperationContract()]
       public int Add(int num1, int num2)
       {
           return num1 + num2;
       }

   }
Now you have some fundamental idea on Service contract. Next we will look into Data Contract.

Metadata Exchange Endpoint

Exposing the metadata using HTTP-GET has a disadvantage, such that there is no guarantee that other platforms you interact will support it. There is other way of exposing the using special endpoint is called as Metadata Exchange Endpoint. You can have as many metadata exchange endpoints as you want.

Address

It is basically Uri to identify the metadata. You can specify as address in the endpoint but append with "mex" keyword. For example "http://localhost:9090/MyCalulatorService/mex"

Binding

There are four types of bindings supported for metadata exchange. They are mexHttpBinding, mexHttpsBinding, mexNamedPipesBinding, mexTcpBinding.

Contract

IMetadataExchange is the contract used for MEX endpoint. WCF service host automatically provides the implementation for this IMetadataExcahnge while hosting the service.
You can create the Metadata Exchange Endpoint either Administrative (configuration file) or programmatically.

Administrative (Configuration file):

In the configuration file of the hosting application, you can add metadata exchange endpoint as shown below.
<system.serviceModel>
<services>
 <service name="MyService">
 <endpoint address="http://localhost/IISHostedService/MyService.svc"
 binding="wsHttpBinding" contract="IMyService">
 <identity>
 <dns value="localhost"/>
 </identity>
 </endpoint>
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
 </service>
</services>  
</system.serviceModel>

Programming Model:

In the following code I have mention about creating the Metadata Exchange Endpoint through coding. Steps to create the metadata endpoint are
  • Create the ServiceMetadataBehavior object and add to Service host description.
  • ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                host.Description.Behaviors.Add(smb);
  • Create the metadata binding object using MetadataExchangeBinding
  • Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding ();
  • 3. Add the endpoint to the service host with address, binding and contract.
  • host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
Complete code for hosting the service with metadata exchange endpoint is shown below.
//Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
            //Create ServiceHost
            ServiceHost host = new 
            ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
            //Add a service endpoint
            host.AddServiceEndpoint
            (typeof(MyCalculatorService.ISimpleCalculator), new WSHttpBinding(), "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            host.Description.Behaviors.Add(smb);
            Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding ();
            //Adding metadata exchange endpoint
            host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
            //Start the Service
            host.Open();

            Console.WriteLine("Service is host at " + DateTime.Now.ToString());
            Console.WriteLine("Host is running... Press  key to stop");

HTTP_GET Enabled Metadata

We will use ServiceBehaviour to publish the metadata using HTTP-GET. This can be configures either administratively or Programmatically. Http and Https can expose by appending "?wsdl" to the end of the service address. For example service address is http://localhost:9090/MyCalulatorService , HTTP-Get metadata address is given by http://localhost:9090/MyCalulatorService?wsdl.

Administrative (Configuration file):

In the below mention configuration information, you can find the behavior section in the ServiceBehavior. You can expose the metadata using ServiceMetadata node with httpGetEnable='True'.
<system.serviceModel>
   <services>
 <service behaviorConfiguration="ServiceBehavior" name="MyService">
    <endpoint address="http://localhost/IISHostedService/MyService.svc"
     binding="wsHttpBinding" contract="IMyService">
  <identity>
  <dns value="localhost"/>
  </identity>
     </endpoint>
 </service>
  </services>
  <behaviors>
    <serviceBehaviors>
 <behavior name="ServiceBehavior">
   <!-Setting httpGetEnabled you can publish the metadata -->
  <serviceMetadata httpGetEnabled="true"/>
  </behavior>
     </serviceBehaviors>
   </behaviors>
</system.serviceModel>

Progarmming Model:

Using ServiceMetadataBehavior you can enable the metadata exchange. In the following code, I have created the ServiceMetadataBehavior object and assigned HttpGetEnabled property to true. Then you have to add the behavior to host description as shown. This set of code will publish the metadata using HTTP-GET.
 //Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
            //Create ServiceHost
            ServiceHost host = new 
            ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
            //Add a service endpoint
            host.AddServiceEndpoint
            (typeof(MyCalculatorService.ISimpleCalculator), new WSHttpBinding(), "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

            //Enable metadata exchange using HTTP-GET
            smb.HttpGetEnabled = true;

            host.Description.Behaviors.Add(smb);
            //Start the Service
            host.Open();
            Console.WriteLine("Service is host at " + DateTime.Now.ToString());
            Console.WriteLine("Host is running... Press  key to stop");
            Console.ReadLine();

Binding configuration

Binding can be configured either through configuration file or Programming. Let us see the binding representation in each method.

Administrative (Configuration file):

In the configuration file of the hosting application, you can add the <bindings> element inside the <system.serviceModel> element and add the properties to particular binding type. Properties corresponding to the particular binding type can be mentioned below. Name of the binding properties that you are going to use has to be mention in the end point.
<system.serviceModel>
  <services>
   <service  name="MyService">
 <endpoint address="http://localhost/IISHostedService/MyService.svc" 
 binding="wsHttpBinding" bindingName="wshttpbind" contract="IMyService">
 <identity>
 <dns value="localhost"/>
 </identity>
 </endpoint>
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
  </services>
  <bindings>
      <wsHttpBinding>
        <binding name="wshttpbind"  allowCookies="true" closeTimeout="00:01:00" 
        receiveTimeout="00:01:00" />
      </wsHttpBinding>
  </bindings>
</system.serviceModel>

Programming Model:

In the following code, I have created the WSHttpBinding object and assign the properties which to be configured. This binding object is added to the Service endpoint for client communication. Similarly you can also create any type of binding and add to endpoint.
//Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
            //Create ServiceHost
            ServiceHost host =
             new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);

            //Create Binding to add to end point
            WSHttpBinding wshttpbind = new WSHttpBinding();
            wshttpbind.AllowCookies = true;
            wshttpbind.CloseTimeout = new TimeSpan(0, 1, 0);
            wshttpbind.ReceiveTimeout  = new TimeSpan(0, 1, 0);

            //Add a service endpoint
            host.AddServiceEndpoint
            (typeof(MyCalculatorService.ISimpleCalculator), wshttpbind, "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);
            //Start the Service
            host.Open();

            Console.WriteLine("Service is host at " + DateTime.Now.ToString());
            Console.WriteLine("Host is running... Press  key to stop");
            Console.ReadLine();

Note: It is always good if you configure the binding properties using configuration file, because while moving to the production you no need to change in the code and recompile it. It is always good practice to represent in the configuration file.

Types of Binding

Let us see more detailed on predefined binding

BasicHttpBinding

  • It is suitable for communicating with ASP.NET Web services (ASMX)-based services that comfort with WS-Basic Profile conformant Web services.
  • This binding uses HTTP as the transport and text/XML as the default message encoding.
  • Security is disabled by default
  • This binding does not support WS-* functionalities like WS- Addressing, WS-Security, WS-ReliableMessaging
  • It is fairly weak on interoperability.

WSHttpBinding

  • Defines a secure, reliable, interoperable binding suitable for non-duplex service contracts.
  • It offers lot more functionality in the area of interoperability.
  • It supports WS-* functionality and distributed transactions with reliable and secure sessions using SOAP security.
  • It uses HTTP and HTTPS transport for communication.
  • Reliable sessions are disabled by default.

WSDualHttpBinding

This binding is same as that of WSHttpBinding, except it supports duplex service. Duplex service is a service which uses duplex message pattern, which allows service to communicate with client via callback.
In WSDualHttpBinding reliable sessions are enabled by default. It also supports communication via SOAP intermediaries.

WSFederationHttpBinding

This binding support federated security. It helps implementing federation which is the ability to flow and share identities across multiple enterprises or trust domains for authentication and authorization. It supports WS-Federation protocol.

NetTcpBinding

This binding provides secure and reliable binding environment for .Net to .Net cross machine communication. By default it creates communication stack using WS-ReliableMessaging protocol for reliability, TCP for message delivery and windows security for message and authentication at run time. It uses TCP protocol and provides support for security, transaction and reliability.

NetNamedPipeBinding

This binding provides secure and reliable binding environment for on-machine cross process communication. It uses NamedPipe protocol and provides full support for SOAP security, transaction and reliability. By default it creates communication stack with WS-ReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery and binary encoding.

NetMsmqBinding

  • This binding provides secure and reliable queued communication for cross-machine environment.
  • Queuing is provided by using MSMQ as transport.
  • It enables for disconnected operations, failure isolation and load leveling

NetPeerTcpBinding

  • This binding provides secure binding for peer-to-peer environment and network applications.
  • It uses TCP protocol for communication
  • It provides full support for SOAP security, transaction and reliability.

Bindings and Channel Stacks

In WCF all the communication details are handled by channel, it is a stack of channel components that all messages pass through during runtime processing. The bottom-most component is the transport channel. This implements the given transport protocol and reads incoming messages off the wire. The transport channel uses a message encoder to read the incoming bytes into a logical Message object for further processing.
Figure 1: Bindings and Channel Stacks (draw new diagram)
After that, the message bubbles up through the rest of the channel stack, giving each protocol channel an opportunity to do its processing, until it eventually reaches the top and WCF dispatches the final message to your service implementation. Messages undergo significant transformation along the way.
It is very difficult for the developer to work directly with channel stack architecture. Because you have to be very careful while ordering the channel stack components, and whether or not they are compatible with one other.
So WCF provides easy way of achieving this using end point. In end point we will specify address, binding and contract. To know more about end point. Windows Communication Foundation follows the instructions outlined by the binding description to create each channel stack. The binding binds your service implementation to the wire through the channel stack in the middle.

Windows Service Hosting

In this tutorial we are going to see the hosting WCF service in Windows service. We will use same set of code used for hosting the WCF service in Console application to this. This is same as hosting the service in IIS without message activated. There is some advantage of hosting service in Windows service.
  • The service will be hosted, when system starts
  • Process life time of the service can be controlled by Service Control Manager for windows service
  • All versions of Windows will support hosting WCF service.
Step 1: Now let start create the WCF service, Open the Visual Studio 2008 and click New->Project and select Class Library from the template.
Step 2: Add reference System.ServiceModel to the project. This is the core assembly used for creating the WCF service.
Step 3: Next we can create the ISimpleCalulator interface as shown below. Add the Service and Operation Contract attribute as shown below.
ISimpleCalculator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace WindowsServiceHostedContract
{
    [ServiceContract]
    public interface ISimpleCalculator
    {
        [OperationContract]
        int Add(int num1, int num2);

        [OperationContract]
        int Subtract(int num1, int num2);

        [OperationContract]
        int Multiply(int num1,int num2);

        [OperationContract]
        double Divide(int num1, int num2);

    }
}
Step 4: Implement the ISimpleCalculator interface as shown below.
SimpleCalulator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsServiceHostedService
{
    class SimpleCalculator
        : ISimpleCalculator
    {
 
        public int Add(int num1, int num2)
        {
            return num1+num2;
        }

        public int Subtract(int num1, int num2)
        {
             return num1-num2;
        }

        public int Multiply(int num1, int num2)
        {
             return num1*num2;
        }

        public double Divide(int num1, int num2)
        {
            if (num2 != 0)
                return num1 / num2;
            else
                return 0;
        }


    }
}
Step 5: Build the Project and get the dll. Now we are ready with WCF service, now we are going to see how to host the WCF Service in Windows service. Note: In this project, I have mention that we are creating both Contract and Service(implementation) are in same project. It is always good practice if you have both in different project.
Step 6: Open Visual Studio 2008 and Click New->Project and select Windows Service.
Step 7: Add the 'WindowsServiceHostedService.dll' as reference to the project. This assembly will going to act as service.
Step 8: OnStart method of the service, we can write the hosting code for WCF. We have to make sure that we are using only one service host object. On stop method you need to close the Service Host. Following code show how to host WCF service in Windows service.
WCFHostedWindowsService.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace WCFHostedWindowsService
{
    partial class WCFHostedWindowsService : ServiceBase
    {
        ServiceHost m_Host;
        
        public WCFHostedWindowsService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            if (m_Host != null)
            {
                m_Host.Close();
            }
            //Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
            //Create ServiceHost
            m_Host = new ServiceHost
            (typeof(WindowsServiceHostedService.SimpleCalculator), httpUrl);
            //Add a service endpoint
            m_Host.AddServiceEndpoint
            (typeof(WindowsServiceHostedService.ISimpleCalculator), new WSHttpBinding(), "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            m_Host.Description.Behaviors.Add(smb);
            //Start the Service
            m_Host.Open();


        }

        protected override void OnStop()
        {
            if (m_Host != null)
            {
                m_Host.Close();
                m_Host = null;
            }
        }
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
   { 
    new WCFHostedWindowsService() 
   };
            ServiceBase.Run(ServicesToRun);

        }
    }
}
Step 9: In order to install the service we need to have the Installer class for the Windows service. So add new Installer class to the project, which is inherited from the Installer class. Please find the below code for mentioning the Service name, StartUp type etc of the service.
ServiceInstaller.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceProcess;
using System.Configuration.Install;
using System.ComponentModel;
using System.Configuration;


namespace WCFHostedWindowsService
{
    [RunInstaller(true)]
    public class WinServiceInstaller : Installer
    {
        private ServiceProcessInstaller process;
        private ServiceInstaller service;

        public WinServiceInstaller()
        {
            process = new ServiceProcessInstaller();
            process.Account = ServiceAccount.NetworkService;
            service = new ServiceInstaller();
            service.ServiceName = "WCFHostedWindowsService";
            service.DisplayName = "WCFHostedWindowsService";
            service.Description = "WCF Service Hosted";
            service.StartType = ServiceStartMode.Automatic;
            Installers.Add(process);
            Installers.Add(service);
        }
    }
}
Step 10: Build the project, we will get the WCFHostedWindowsService.exe. Next we need to install the service using Visual Studio Command Prompt. So open the command prompt by clicking Start->All Programs-> Microsoft Visual Studio 2008-> Visual Studio Tools-> Visual Studio Command Prompt Using installutil utility application, you can install the service as shown below.
Step 11: Now service is Hosted sucessfully and we can create the proxy class for the service and start using in the client applcaiton.

Wednesday, September 5, 2012

Adding Page Title, Meta Tags dynamically in ASP.NET

Untitled Document using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page.Title = "This is the page title";

// Create two instances of an HtmlMeta control.

HtmlMeta hm1 = new HtmlMeta();

HtmlMeta hm2 = new HtmlMeta();

// Define an HTML <meta> element - description - that is useful for search engines.
hm1.Name = "description";
hm1.Content = "this is the description text of the meta tag";

// Define an HTML <meta> element - keywords - that is useful for search engines.
hm2.Name = "keywords";
hm2.Content = "these are the keywords of the meta tag";

// Get a reference to the page header element.

HtmlHead head = (HtmlHead)Page.Header;

head.Controls.Add(hm1);

head.Controls.Add(hm2);

}
}