10 March 2014

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 [Data Member] 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 [Data Member] 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
        }

6 March 2014

Service Contract

         Service contract describes the operation that service provides. A Service can have more than one service contract but it should have at least one Service contract.
            
          Service Contract can be define using [Service Contract] and [Operation Contract] attribute. [Service Contract] attribute is similar to the [Web Service] attribute in the Web Service and [Operation Contract] is similar to the [Web Method] in Web Service.
  • 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 Service Contract Attribute to indicate it is a service contract. Methods in the interface that should be included in the service contract are decorated with the Operation Contract Attribute.
Service contract describes the operation that service provides.
     
        A Service can have more than one service contract but it should have at least one Service contract.Service Contract can be define using [Service Contract] and [Operation Contract] attribute. [Service Contract] attribute is similar to the [Web Service] attribute in the Web Service and [Operation Contract] is similar to the [Web Method] in Web Service.
  • 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 Service Contract Attribute to indicate it is a service contract. Methods in the interface that should be included in the service contract are decorated with the Operation Contract Attribute.
  

 [Service Contract()]
    Public interface ISimpleCalculator
    {
        [Operation Contract ()]
        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;
        } 
    }

     Without 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
[Service Contract ()]
 Public class SimpleCalculator
 {
    [Operation Contract ()]
    Public int Add (int num1, int num2)
    {
         Return num1 + num2;
      } 
   }




Contracts and Service Host -WCF Fundamentals

Contracts:
   
         In WCF, all services are exposed as contracts. Contract is a platform-neutral and standard way of describing what the service does. Mainly there are four types of contracts available in WCF

       
       Service Contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.




        Data Contract describes the custom data type which is exposed to the client. This defines the data types, that are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using Data Contract we can make client to be aware of Employee data type that are returning or passing parameter to the method.



  Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute
     


 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 ContractFault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.      

Service Host:

        Service Host object is in the process of hosting the WCF service and registering endpoints. It loads the service configuration endpoints, apply the settings and start the listeners to handle the incoming request. System.ServiceModel.ServiceHost namespace hold this object. This object is created while self hosting the WCF service.

       In the below example you can find that WCF service is self hosted using console application.
//Creating uri for the hosting the service

  Uri uri = new Uri("http://localhost/CategoryService");

//Creating the host object for Math Service

  ServiceHost host = new ServiceHost(typeof(CategoryService), uri);

//Adding endpoint to the Host object

  host.AddServiceEndpoint(typeof(ICategoryService),new WSHttpBinding(), uri);

  host.Open(); //Hosting the Service

  Console.WriteLine("Waiting for client invocations");

  Console.ReadLine();

  host.Close();



Bindings and Behaviours --Fundamentals of WCF

Bindings:

       This describes about how to communicate with service.

      For an instance Consider a scenario say, I am creating a service that has to be used by two type of client. One of the clients will access SOAP using http and other client will access Binary using TCP. How it can be done? With Web service it is very difficult to achieve, but in WCF it’s just we need to add extra endpoint in the configuration file

<system.serviceModel>
    <services>
      <service name="MathService"
        BehaviorConfiguration="MathServiceBehavior">
      <endpoint address="http://localhost:8090/MyService/MathService.svc"
        Contract="IMathService" binding="wsHttpBinding"/>
<endpoint address="net.tcp://localhost:8080/MyService/MathService.svc"
Contract="IMathService"    binding="netTcpBinding"/>
      </service>
    </services>
    <Behaviors>
      <ServiceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

      In above instance common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations.

Behavior:

  In the below configuration information, I have mentioned the Behavior at Service level. In the service behavior I have mention the serviceMetadata node with attribute httpGetEnabled='true'. This attribute will specifies the publication of the service metadata. Similarly we can add more behavior to the service.
<system.serviceModel>
    <services>
      <service name="MathService"
        BehaviorConfiguration="MathServiceBehavior">
        <endpoint address="" contract="IMathService"
          binding="wsHttpBinding"/>
      </service>
    </services>
    <Behaviors>
      <ServiceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel> 

Note:

     Application can be controlled either through coding, configuring or through combination of both. Specification mention in the configuration can also be overwritten in code.

   </behavior>

      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

      In above instance common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations.
   

3 March 2014

WCF Architecture


  The major components  of WCF service 

 Contracts:

    Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

Service contracts:

     Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

Data contract:

     It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data type cannot be identified by the client e.g. Employee data type. By using Data Contract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

Message Contract:

    Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Policies and Binding:

    Specify conditions required to communicate with a service e.g. security requirement to communicate with service, protocol and encoding used for binding.

Service Runtime:

   It contains the behaviors that occur during runtime of service.
  • Throttling Behavior- Controls how many messages are processed.
  • Error Behavior - Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior - Tells how and whether metadata is available to outside world.
  • Instance Behavior - Specifies how many instance of the service has to be created while running.
  • Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.
Messaging:

   Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint.

   Broadly we can categories channels as Transport Channel and Protocol Channel

Transport Channels:

    Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.

Protocol Channels:

     Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.