Various Types of WCF Contracts

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.

A. Service Contracts

  1. Service Contract
  2. Operation Contract

1. Service Contract

The Service Contract declares an interface in the WCF service for the client to get access to the interface.

  1. [ServiceContract]    
  2. interface ICustomer    
  3. {    
  4.   
  5. }  

2. Operation Contract

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

  1. [OperationContract]    
  2. Response AddNew(string customername);   

Example 2

  1. [ServiceContract]    
  2. interface ICustomer    
  3. {    
  4.     [OperationContract]    
  5.     Response AddNew(string customername);    
  6.     Response Delete(int customerID);    
  7. }   

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.

B. 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.

  • 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.
    1. [DataContract]    
    2. public class Customer    
    3. {    
    4. }
  • 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.

    Example
    1. [DataContract]    
    2. public class Customer    
    3. {    
    4.     [DataMember]    
    5.     public int ID { getset; }    
    6.     [DataMember]    
    7.     public string Name { getset; }    
    8.         public string ContactNo { getset; }    
    9. }   
    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.

C. 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.

Example 1: Example of declaring a FaultContract in the service.

  1. [ServiceContract]    
  2. public interface IService1    
  3. {    
  4.     [OperationContract]    
  5.     [FaultContract(typeof(ServiceData))]    
  6.     ServiceData TestConnection(string strConnectionString);    
  7. }  

Example 2: Use of FaultContract in the client.

  1. namespace FaultContractSampleWCF    
  2. {    
  3.         
  4.     public class Service1 : IService1    
  5.     {    
  6.         public ServiceData TestConnection(string StrConnectionString)    
  7.         {    
  8.             ServiceData myServiceData = new ServiceData();    
  9.             try    
  10.             {    
  11.                 SqlConnection con = new SqlConnection(StrConnectionString);    
  12.                 con.Open();    
  13.                 myServiceData.Result = true;    
  14.                 con.Close();    
  15.                 return myServiceData;    
  16.             }    
  17.             catch (SqlException sqlEx)    
  18.             {    
  19.                 myServiceData.Result = true;    
  20.                 myServiceData.ErrorMessage = "Connection can not open this " +     
  21.                    "time either connection string is wrong or Sever is down. Try later";    
  22.                 myServiceData.ErrorDetails = sqlEx.ToString();    
  23.                 throw new FaultException<ServiceData>(myServiceData, sqlEx.ToString());    
  24.             }    
  25.             catch (Exception ex)    
  26.             {    
  27.                 myServiceData.Result = false;    
  28.                 myServiceData.ErrorMessage = "unforeseen error occurred. Please try later.";    
  29.                 myServiceData.ErrorDetails = ex.ToString();    
  30.                 throw new FaultException<ServiceData>(myServiceData, ex.ToString());    
  31.             }    
  32.         }    
  33.     }    

Example 3: Consuming FaultContract in the client.

  1. class Program    
  2. {    
  3.     static void Main(string[] args)    
  4.     {    
  5.         try    
  6.         {    
  7.             Service1Client objServiceClient = new Service1Client();    
  8.             //Pass the connection string to the TestConnection Method.    
  9.             ServiceData objSeviceData = objServiceClient.TestConnection(    
  10.               @"integrated security=true;data source=localhost;initial catalog=master");    
  11.             if (objSeviceData.Result == true)    
  12.                 Console.WriteLine("Connection Succeeded");    
  13.             Console.ReadLine();    
  14.         }    
  15.         catch (FaultException<ServiceData> Fex)    
  16.         {    
  17.             Console.WriteLine("ErrorMessage::" + Fex.Detail.ErrorMessage + Environment.NewLine);    
  18.             Console.WriteLine("ErrorDetails::" + Environment.NewLine + Fex.Detail.ErrorDetails);    
  19.             Console.ReadLine();    
  20.         }    
  21.     }    

D. 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.

  1. [MessageContract]    
  2. public class EmployeeDetails    
  3. {    
  4.     [MessageHeader(ProtectionLevel=ProtectionLevel.None)]    
  5.     public string EmpID;    
  6.     [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign )]    
  7.     public string Name;    
  8.     [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign )]    
  9.     public string Designation;    
  10.     [MessageBodyMember(ProtectionLevel=ProtectionLevel.EncryptAndSign)]    
  11.     public int Salary;    
  12.   
  13. }  

Example: Use of MessageContract in service.

  1. [ServiceContract]    
  2. interface ICuboidService    
  3. {    
  4.     [OperationContract]    
  5.     [FaultContract(typeof(CuboidFaultException))]    
  6.     CuboidDetailResponse CalculateDetails1(CuboidInfoRequest cInfo);    
  7.        
  8.     [OperationContract]    
  9.     [FaultContract(typeof(CuboidFaultException))]    
  10.     CuboidDetail CalculateDetails2(CuboidInfo cInfo);    
  11.      
  12.     [OperationContract]    
  13.     [FaultContract(typeof(CuboidFaultException))]    
  14.     CuboidDetail CalculateDetails3(int nID, CuboidDimension cInfo);    

Summary

I hope you have gotten the details of the various contracts that WCF supports.


Similar Articles