WCF Contracts

Kailash Chandra Behera | Wednesday, June 22, 2016

Introduction

This article describes about the contracts, various types of contracts are available in WCF and use of the contracts.

Getting Started

A WCF contract defines what a service does or what action a client can perform in the service. The contract is one of the elements of a WCF endpoint that contains information about the WCF service. The contract also helps to serialize service information. There are two type of contracts, one is Service Contracts, Data Contracts, Fault Contract and Message Contract.

Service Contracts

The Service Contracts describes what action a client can perform in a service. This attribute is in the System.ServiceModel namespace. There are the following two types.
  1. Service Contract
  2. The Service Contract declares an interface in the WCF service for the client to get access to the interface.

     [ServiceContract]    
     interface ICustomer    
     {    
     }   
    

  3. Operation Contract
  4. The Operation Contract declares a function inside the interface, the client will call this function. If you don't use the Operation contract in the preceding function then the client will not be able to call the function. Example 1

     [OperationContract]    
     Response AddNew(string customername);  
    
    Example 2
     [ServiceContract]    
     interface ICustomer    
     {    
       [OperationContract]    
       Response AddNew(string customername);    
       Response Delete(int customerID);    
     }   
    
    In the preceding Example 2 the clients will not be able to call the function name delete because the delete function has not used the Operation Contract.

Data Contracts

A Data Contract defines what data type to be passed to or from the client. In the WCF service, the Data Contract takes a major role for serialization and deserialization. There are two types of Data Contracts.

  1. Data Contract

    This contract declares and defines the class to be serialized for the client to access. If the Data Contract tag is not used then the class will not be serialized or deserialized.

     [DataContract]    
     public class Customer    
     {    
     }  
    

  2. Data Member

    This declares and defines properties inside a class, the property that doesn't use a Data Member tag will not be serialized or deserialized.

     [DataContract]    
     public class Customer    
     {    
       [DataMember]    
       public int ID { get; set; }    
       [DataMember]    
       public string Name { get; set; }    
         public string ContactNo { get; set; }    
     }    
    
    In the preceding example the ContactNo property will not be given access to the client because it will not be serialized or deserialized though it is not used as a Data Member attribute.

Fault Contracts

In a simple WCF Service, errors/exceptions can be passed to the Client (WCF Service Consumer) using FaultContract. The fault contract defines the error to be raised by the service and how the service handles and propagates the error to its clients.

  1. Example of declaring a FaultContract in the service.
     [ServiceContract]    
     public interface IService1    
     {    
       [OperationContract]    
       [FaultContract(typeof(ServiceData))]    
       ServiceData TestConnection(string strConnectionString);    
     }   
    
  2. Example for using of FaultContract in the server.
     namespace FaultContractSampleWCF    
     {    
       public class Service1 : IService1    
       {    
         public ServiceData TestConnection(string StrConnectionString)    
         {    
           ServiceData myServiceData = new ServiceData();    
           try    
           {    
             SqlConnection con = new SqlConnection(StrConnectionString);    
             con.Open();    
             myServiceData.Result = true;    
             con.Close();    
             return myServiceData;    
           }    
           catch (SqlException sqlEx)    
           {    
             myServiceData.Result = true;    
             myServiceData.ErrorMessage = "Connection can not open this " +     
               "time either connection string is wrong or Sever is down. Try later";    
             myServiceData.ErrorDetails = sqlEx.ToString();    
             throw new FaultException<ServiceData>(myServiceData, sqlEx.ToString());    
           }    
           catch (Exception ex)    
           {    
             myServiceData.Result = false;    
             myServiceData.ErrorMessage = "unforeseen error occurred. Please try later.";    
             myServiceData.ErrorDetails = ex.ToString();    
             throw new FaultException<ServiceData>(myServiceData, ex.ToString());    
           }    
         }    
       }    
     }   
    
  3. Consuming FaultContract in the client.
     class Program    
     {    
       static void Main(string[] args)    
       {    
         try    
         {    
           Service1Client objServiceClient = new Service1Client();    
           //Pass the connection string to the TestConnection Method.    
           ServiceData objSeviceData = objServiceClient.TestConnection(    
            @"integrated security=true;data source=localhost;initial catalog=master");    
           if (objSeviceData.Result == true)    
             Console.WriteLine("Connection Succeeded");    
           Console.ReadLine();    
         }    
         catch (FaultException<ServiceData> Fex)    
         {    
           Console.WriteLine("ErrorMessage::" + Fex.Detail.ErrorMessage + Environment.NewLine);    
           Console.WriteLine("ErrorDetails::" + Environment.NewLine + Fex.Detail.ErrorDetails);    
           Console.ReadLine();    
         }    
       }    
     }   
    

Message Contract

A MessageContract controls the structure of a message body and serialization process. It is also used to send / access information in SOAP headers. By default, WCF takes care of creating SOAP messages depending on the service's DataContracts and OperationContracts. A MessageContract can be typed or untyped and are useful in iteroperability cases and when there is an existing message format we must comply with. Most of the time the developer concentrates more on developing the DataContract, serializing the data and so on. Sometimes the developer will also require control of the SOAP message format. In that case WCF provides the MessageContract to customize the message depending on requirements. MessageContract is in System.Net.Security.
Example: Declaration of MessageContract.

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

Related Articles

  1. WCF Address
  2. WCF Endpoints
  3. WCF Bindings

Summary

In the above of this article we have discussed what is contract, various type of contract in WCF, I hope you have got the details of the discussion about contracts that WCF supports.

Thanks