Wednesday 1 August 2012

WCF : Contracts


1.    What are 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.
2.    What are various types of contracts
ü  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 Contracts:
ü  Data contract describes the custom data types which are 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.

ü  Fault Contracts: Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.

ü  Message Contracts: 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.
3.    Explain 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 [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.
4.    How you will create a service contract. Explain
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;
        }

    }
5.    Can I create a service contract without creating an interface?
      Yes. Without creating the interface, we can also directly create 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;
       }

   }
6.    Can you overload a method you have defined in the operation contract?
     By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContractattribute, we can deal with operation overloading scenario. 
    [ServiceContract]

interface ICalculator

{

   [OperationContract(Name = "AddInt")]

   int Add(int arg1,int arg2);



   [OperationContract(Name = "AddDouble")]

   double Add(double arg1,double arg2);

}
7.    Suppose you have created a WCF service. You have an interface stating your methods that must be exposed to the clients. But you have forgotten to specify "[OperationContract]" attribute in any of your method. What will happen?

If you do not specify "[OperationContract]” in any of the methods in your interface then you will get the following error:-

IService1' has zero operations; a contract must have at least one operation

So, it is mandatory to label "[OperationContract]” attribute to at least one method while declaring your interface methods or ServiceContract.

8.    Explain in brief, WCF One Way Contract?

ü  WCF One Way Contract is methods/operations which are invoked on the service by the client or the server in which either of them do not expect a reply back.
ü  If a client invokes a method on the service then it will not expect a reply back from the service.

9.    What is the most primary reason to use WCF One Way Contract?
One way contract is used to ensure that the WCF client does not go in a blocking mode. If your WCF operation contracts are returning nothing and they are doing some heavy process then it is better to use one way contract.

10.How is WCF One Way Contract is implemented ?

WCF one way contract is implemented via "IsOneWay = true/false" attribute.
For example:-
     [ServiceContract]
     interface IMyContract
     {
      [OperationContract(IsOneWay = true)]
      void MyMethod( );
       }

11.In WCF, while using one way contract, suppose a client invokes a method and the server while executing it, encounters an error. Will the error message propagate to the client or will the client ever know that there was an error on the server side?

No, one-way operations cannot return values and any exception thrown on the service side will not make its way to the client. The client will never know whether there was an error or not!
12.In WCF, what is the default value of IsOneWay property?

By default IsOneWay property is false. You must explicitly specify the value of the attribute property to be true if you want a one-way contract for the method. 

13.Is the below code correct: -
      [ServiceContract]
       interface IMyContract
        {
      [OperationContract(IsOneWay = true)]
       int MyMethod( );
     }

No, there should be no reply associated with a one-way operation. In the above an integer value is returned even though the IsOneWay property is true! 


14.What is a 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.
ü  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
ü  It 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
15.What is the namespace for DataContract in WCF?
System.Runtime.Serialization

16.    What does the namespace "System.Runtime.Serialization" exactly do in WCF ?
ü  WCF uses the class to convert objects into a stream of data suitable for transmitting over the network (this process is known as Serialization). It also uses them to convert a stream of data received from the network back into objects (De-Serialization).

17.  Give an example of a data contract
    [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

    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
        }
18.Can a DataContract Classes inherit one another?

If we use the general method to inherit DataContract classes , metadata fails to load.
To inherit DataContract classes , we need to add KnownType attribute to the class.
     [DataContract] 
     public class A 
{ 
      [DataMember] 
     public MyCustomType AValue1{ get; set; } 
        [DataMember] 
        public MyCustomType AValue2 { get; set; } 
} 
[DataContract] 
public class B: A 
{ 
[DataMember] 
public double BValue1{ get; set; } 
[DataMember] 
public double BValue2 { get; set; } 
} 



Above fails to load the metadata.
So, following should be done.

    [DataContract] 
[KnownType(typeof(B))] 
public class A 
{ 
[DataMember] 
public string Value { get; set; } 
} 

[DataContract] 
public class B : A 
{ 
[DataMember] 
public string OtherValue { get; set; } 
}

19.In what are the different ways a WCF Metadata can be accessed ?
 WCF Metadata can be accessed in two ways :- 
ü  WSDL document can be generated which represents the endpoints and protocols 
ü  Or the ServiceHost can expose a metadata exchange endpoint to access metadata at runtime
20.In WCF, can a struct be used as a DataContract ?
Yes, a struct can be used as a DataContract. For example :-
       [DataContract]
     struct EmployeeInfo
       {
      [DataMember]
     public int id;
       [DataMember]
      public string name;
      [DataMember]
      public DateTime joining_date;
      }


21.What happens if we apply DataMember attributes to Static Fields?
ü  If we apply DataMember attributes to Static Fields, the system won't give any exception but it simple ignores it. 
ü  The Information provided by an attribute is also known as metadata.
22.What is data contract equivalence?
Two data contracts are said to be equivalent, if they satisfy the following conditions.
ü  Both the datacontracts must have same namespace
ü   Both the datacontracts must have same name
ü  The data member on data contract must have an equivalent data member on the other.
ü  The members in the datacontract must appear in the same order in both datacontracts.
ü  Ex: The following two data contracts are equal.
     [DataContract]

     public class Person
  
     {

    [DataMember]

    public string Name;



    [DataMember]

    public string Email_ID;

     }



     [DataContract(Name = "Person")]

      public class Employee

     {

    [DataMember(Name = "Name")]

    private string EmpName;



    private string address;



    [DataMember(Name = "Email_ID")]

    private string EmpEmailId;

      }

23.What is a message?
Message is the packet of data which contains important information. WCF uses these messages to transfer information from Source to destination.

24.What is SOAP?
SOAP: Simple Object Access Protocol

25.Explain how communication happens in WCF?
ü  WCF uses SOAP(Simple Object Access Protocol) Message format for communication.
ü  SOAP message contain Envelope, Header and Body. SOAP envelope contails name, namespace, and header and body element.
ü  SOAP Head contain important information which is not directly related to message.
ü  SOAP body contains information which is used by the target.


26.Can you explain message pattern?
ü  There are three way of communication between source and destination
·         Simplex - It is one way communication. Source will send message to target, but target will not respond to the message.
·         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
·         Duplex - It is two way communication, both source and target can send and receive message simultaneously.
27.What is a message contract?
ü  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.
28.Give an example of a 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.
29.What are the various rules for a message contract?
ü  When using Message contract type as parameter, Only one parameter can be used in servicie Operation
     [OperationContract]
    void SaveEmployeeDetails(EmployeeDetails emp);
ü  Service operation either should return Messagecontract type or it should not return any value
    [OperationContract]
   EmployeeDetails GetEmployeeDetails();
ü  Service operation will accept and return only message contract type. Other data types are not allowed.
   [OperationContract]
    EmployeeDetails ModifyEmployeeDetails(EmployeeDetails emp);
30.Can a type have both data and message contract?
ü  If a type has both Message and Data contract, service operation will accept only message contract.
31.Explain Fault contract.
ü  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.
32.Explain steps to create a fault contract.
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");
           
        }
33.Can you create custom fault contracts?
Yes, You can also create your own Custom type and send the error information to the client using FaultContract.
34.What are the steps to create a fault contract?
ü  Define a type using the data contract and specify the fields you want to return.
    [DataContract()]
    public class CustomException
    {
        [DataMember()]
        public string Title;
        [DataMember()]
        public string ExceptionMessage;
        [DataMember()]
        public string InnerException;
        [DataMember()]
        public string StackTrace;        
    }

ü  Decorate the service operation with the FaultContract attribute and specify the type name.
    [ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        [FaultContract(typeof(CustomException))]
        int Add(int num1, int num2);
    }

ü  Raise the exception from the service by creating an instance and assigning properties of the custom exception.
           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") ;
            
        }
ü  On client side, you can capture the service exception and process the information
   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
     }



No comments:

Post a Comment