Monday, June 4, 2012

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;
       }

   }

Contracts and Service Host

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 Contract

                   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.
To know more on Service contract see ServiceContract page.

Data Contract

                   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 DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.
To know more on DataContract see DataContract page.

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.
To know more on Message Contract see Message contract  Page.

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 occurred in the service to client. This helps us to easy identity, what error has occurred.
To know more on Fault Contract see Fault Contract page.

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 MathService
  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();

Binding and Behavior in WCF


Binding says , how the service could be used. Binding specifies
  1. Which protocol to be used
  2. Which encoding to be used.
  3. What type of security requeiremnet to be used like SSL or SOAP message security.
System provided Bindings

basicHttpBinding
  1. This is interoperable binding.
  2. This is commonly used as replacement for earler web service based on ASMX.
  3. It supports HTTP & HTTPS protocols.
  4. It supports MTOM encoding.
  5. It supports text encoding.
wsHttpBinding
  1. This is a secure binding.
  2. This is interoperable binding.
  3. This uses SOAP over HTTP.
  4. This supports reliability over Internet.
  5. This supports transaction over Internet.
  6. This supports security over Internet.
  7. This supports HTTP/HTTPS proptcol
  8. This supports text and MTOM encoding.
  9. This is default binding provided by WCF.
wsDualHttpBinding
  1. This supports all the feature of wsHttpBinding.
  2. This is mainly used for DUPLEX SERVICE CONTRACTS.
  3. This supports bidirectional communication.
webHttpBinding
  1. This is a secure binding.
  2. This is a interoperable binding.
  3. It supports Http/Https protocol.
  4. It does not use SOAP message format.

    image8.gif
wsFederationHttpBinding
  1. This is a secure Binding.
  2. This is interoperable binding.
  3. This supports federated security
  4. This supports Https/Https protocols.
  5. This uses text/MTOM encoding.

    image9.gif
netTCPBinding
  1. This is a secure Binding.
  2. This could only be used if client is also a WCF machine.
  3. This is used to send Binary encoded SOAP message from one WCF computer to another.
  4. This uses TCP (Transimission Control Protocol)
  5. This supports reliability.
  6. This supports transaction,
  7. This supports security.
netNamedPipeBinding
  1. This is a secure Binding.
  2. This could be used over a single WCF computer.
  3. This sends Binary encoded SOAP message over named pipes.
netMSMQBinding
  1. This is a queued Binding.
  2. This uses Binary encoded SOAP message.
  3. This sends message over MSMQ.
  4. Here communication should occur between two computers.
netPeerTCPBinding
  1. This is a secure Binding.
  2. This uses TCP overe peeer to peer.
  3. Communication should occur between two or more computers.
msmqIntegrationBinding
image10.gif

basicHttpContextBinding
This Binding is same as of basicHttpBinding with more attributes , like below
  1. It supports HTTP cookies
  2. It eanble SOAP haeders to excahnge context.
  3. This binding is mainly used for Durable services.
netTCPContextBinding
This Binding is same as of netTCPBinding with more attributes , like below
  1. It eanble SOAP haeders to excahnge context.
  2. This binding is mainly used for Durable services.
wsHttpContextBinding
This Binding is same as of wsHttpBinding with more attributes , like below
  1. It eanble SOAP haeders to excahnge context.
  2. This binding is mainly used for Durable services.
Example :
<system.serviceModel>
 <services>
 <service name="WcfService2.Service1" behaviorConfiguration="WcfService2.Service1Behavior">
                                      <!-- Service Endpoints -->
<endpoint  address="" binding="wsHttpBinding" contract="WcfService2.IService1">
<!-- Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity automatically.-->
 <identity>
      <dns value="localhost"/>
</identity></endpoint>
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service></services>
 <behaviors>
<serviceBehaviors>
 <behavior name="WcfService2.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
<serviceBehaviors>
</behaviors>
</system.serviceModel>

 
Contract of and EndPoint (C)

image12.gif
  1. Contract should be an Interacfe
  2. Contract could be a class also but better approach is interface.
  3. In config file this is preceded by prpject name space name
<endpoint  address="" binding="wsHttpBinding" contract="WcfService2.IService1">


EndPoint

All communication with a Windows Communication Foundation (WCF) service occurs through the endpoints of the service. Endpoints provide clients access to the functionality offered by a WCF service.
Each endpoint consists of four properties:
  • An Address that indicates where the endpoint can be found.

  • A Binding that specifies how a client can communicate with the endpoint.

  • A Contract that identifies the operations available.

  • A set of behaviors that specify local implementation details of the endpoint.
  
End Point
End Point

Address

Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g
http://localhost:8090/MyService/SimpleCalculator.svc

Binding

Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.
A binding has several characteristics, including the following:
  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability
The following table gives some list of protocols supported by WCF binding.
Binding Description
BasicHttpBinding Basic Web service communication. No security by default
WSHttpBinding Web services with WS-* support. Supports transactions
WSDualHttpBinding Web services with duplex contract and transaction support
WSFederationHttpBinding Web services with federated security. Supports transactions
MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding Communication between WCF applications across computers. Supports duplex contracts and transactions

Contract

Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.


Example:

Endpoints will be mentioned in the web.config file on the created service.
<system.serviceModel>
<services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
       <endpoint
         address="http://localhost:8090/MyService/MathService.svc" 
         contract="IMathService" binding="wsHttpBinding"/> 
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>