Sunday 17 February 2013

Posted by Prasad KM | 23:12 Categories:
WCF Interview Question and Ans

What is the meaning of WCF?
Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

Life Cycle of WCF


What is address in WCF and how many types of transport schemas are there in WCF?

Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.

WCF supports following transport schemas

HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ

The sample address for above transport schema may look like

http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService

what is the meaning of End Point in WCF ?

 WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.All the WCF communications are take place through end point. End point consists of three components.

What is the meaning of  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

What is the meaning of 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

 Types of Data Binding in WCF ?

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

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> 
                                                           

what is the meaning of Service Contract in WCF ?

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

What is the 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.

 

What is the meaning of Message Contract

Message

Message is the packet of data which contains important information. WCF uses these messages to transfer information from Source to destination.
WCF uses SOAP(Simple Object Access Protocol) Message format for communication. SOAP message contain Envelope, Header and Body.SOAP envelope contails name, namespace,header and body element. SOAP Hear contain important information which are not directly related to message. SOAP body contains information which is used by the target.
Diagram Soap envelope

Message Pattern

It describes how the programs will exchange message each other. There are three way of communication between source and destination
  1. Simplex - It is one way communication. Source will send message to target, but target will not respond to the message.
  2. 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
  3. Duplex - It is two way communication, both source and target can send and receive message simultaniouly.

What is Message contract?

As I said earlier, 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.

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

Rules :

You have to follow certain rules while working with Message contract
  1. When using Message contract type as parameter, Only one parameter can be used in servicie Operation
    [OperationContract]
    void SaveEmployeeDetails(EmployeeDetails emp);
    
  2. Service operation either should return Messagecontract type or it should not return any value
    [OperationContract]
    EmployeeDetails GetEmployeeDetails();
    
  3. Service operation will accept and return only message contract type. Other data types are not allowed.
    [OperationContract]
    EmployeeDetails ModifyEmployeeDetails(EmployeeDetails emp); 
     

What is the meaning of Events ?

Events allow the client or clients to be notified about something that has occurred on the service side. An event may result from a direct client call, or it may be the result of something the service monitors. The service firing the event is called the publisher, and the client receiving the event is called the subscriber.

  • Publisher will not care about order of invocation of subscriber. Subscriber can be executed in any manner.
  • Implementation of subscriber side should be short duration. Let us consider the scenario in which you what to publish large volume of event. Publisher will be blocked, when subscriber is queued on previous subscription of the event. These make publishers to put in wait state. It may lead Publisher event not to reach other subscriber.
  • Large number of subscribers to the event makes the accumulated processing time of each subscriber could exceed the publisher's timeout
  • Managing the list of subscribers and their preferences is a completely service-side implementation. It will not affect the client; publisher can even use .Net delegates to manage the list of subscribers.
  • Event should always one-Way operation and it should not return any value

Definition

    public interface IMyEvents
    {
        [OperationContract(IsOneWay = true)]
        void Event1();
    }
Let us understand more on Event operation by creating sample service
Step 1 : Create ClassLibrary project in the Visual Studio 2008 and name it as WCFEventService as shown below.
Step 2: Add reference System.ServiceModel to the project
Create the Event operation at the service and set IsOnwWay property to true. This operation should not return any value. Since service has to communicate to the client, we need to use CallbackContract for duplex communication. Here we are using one operation to subscribe the event and another for firing the event.
public interface IMyEvents
    {
        [OperationContract(IsOneWay = true)]
        void Event1();
    }

   [ServiceContract(CallbackContract = typeof(IMyEvents))]
   public interface IMyContract
   {
       [OperationContract]
       void DoSomethingAndFireEvent();

       [OperationContract]
       void SubscribeEvent();

   }
Step 3: Implementation of the Service Contract is shown below.
In the Subscription operation, I am using Operationcontext to get the reference to the client instance and Subscription method is added as event handler to the service event. DoSomethingAndFireEvent operation will fire the event as shown.
MyPublisher.cs
   [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
   public  class MyPublisher : IMyContract
    {
        static Action m_Event1 = delegate { };

        public void SubscribeEvent()
        {
            IMyEvents subscriber = OperationContext.Current.GetCallbackChannel();
            m_Event1 += subscriber.Event1;
        }

        public static void FireEvent()
        {
            m_Event1();
        }

        public void DoSomethingAndFireEvent()
        {
            MyPublisher.FireEvent();           
        }
    }
Step 4: Create the Console application using Visual Studio 2008 and name it as WcfEventServiceHost. This application will be used to self-host the service.
Step 5: Add System.ServiceModel and WcfEventService as reference to the project.
static void Main(string[] args)
        {
            Uri httpUrl = new Uri("http://localhost:8090/MyPublisher/");
            ServiceHost host = new ServiceHost(typeof(WcfEventService.MyPublisher), httpUrl);
            host.Open();
            Console.WriteLine("Service is Hosted at {0}", DateTime.Now.ToString());
            Console.WriteLine("Host is running...Press  key to stop the service.");
            Console.ReadLine();
            host.Close();
        }
  
Step 6: Use Duplex binding to support Callback operation.
Web.Config
<system.serviceModel>
    <services >
      <service behaviorConfiguration="ServiceBehavior"  
      name="WcfEventService.MyPublisher">
        <endpoint address="http://localhost:8090/MyPublisher" 
        binding="wsDualHttpBinding" contract="WcfEventService.IMyContract">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding"
         contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true "/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
Step7: Run the host application as shown below.
Step 8: Create the console application using visual studio and name it as WcfEventServiceClient as shown below. This application will act a client which is used to subscribe the event from service.
Step 9: Create the proxy class as shown below. Use DuplexClientBase to create the proxy, because it will support bidirectional communication. Create the contractor which will accept InstanceContext as parameter.
EventServiceClient.cs
 class EventServiceClient:DuplexClientBase<IMyContract>,IMyContract 
    {
        public EventServiceClient(InstanceContext eventCntx)
            : base(eventCntx)
        {
            
        }

        public void  DoSomethingAndFireEvent()
        {
            base.Channel.DoSomethingAndFireEvent();
        }

        public void SubscribeEvent()
        {
            base.Channel.SubscribeEvent();
        }
      
    }
Step 10: Implementation of IMyEvents at client side is shown below. This method will be called when service publish the event.
class MySubscriber : IMyEvents
    {
       public void Event1()
        {
            Console.WriteLine("Event is subscribed from the 
            service at {0}",DateTime.Now.ToString() );
        }
  
    }
Step 11: Main method of the client side you can find the creating Subscription instance and it passed to service using InstanceContext
 static void Main(string[] args)
        {
            IMyEvents evnt = new MySubscriber();
            InstanceContext evntCntx = new InstanceContext(evnt);

            EventServiceClient proxy = new EventServiceClient(evntCntx);
            Console.WriteLine("Client subscribe the event
             from the service at {0}",DateTime.Now.ToString());
            proxy.SubscribeEvent();
            Console.WriteLine("Client call operation which will fire the event");
            proxy.DoSomethingAndFireEvent();
            Console.ReadLine();
        }
Step 12: Run the client application and you see the when event is fired from the service. Subscriber got notification.

 

what is the meaning of Two-phase committed protocol ?

Consider the scenario where I am having single client which use single service for communication and interacting with single database. In which service starts and manage the transaction, now it will be easy for the service to manage the transaction.
Consider for example client calling multiple service or service itself calling another service, this type of system are called as Distributed Service-oriented application. Now the questions arise that which service will begin the transaction? Which service will take responsibility of committing the transaction? How would one service know what the rest of the service feels about the transaction? Service could also be deployed in different machine and site. Any network failure or machine crash also increases the complexity for managing the transaction.
In order to overcome these situations, WCF come up with distributed transaction using two way committed protocol and dedicated transaction manager.
Transaction Manager is the third party for the service that will manage the transaction using two phase committed protocol.
Let us see how Transaction manager will manage the transaction using two-phase committed protocols.

 

What is the meaning of  Transaction Propagation ?

In WCF, transaction can be propagated across service boundary. This enables service to participate in a client transaction and it includes multiple services in same transaction, Client itself will act as service or client.
We can specify whether or not client transaction is propagated to service by changing Binding and operational contract configuration
<bindings>
      <netTcpBinding>
        <binding transactionFlow="true"></binding>
      </netTcpBinding>
    </bindings>
Even after enabling transaction flow does not mean that the service wants to use the client’s transaction in every operation. We need to specify the “TransactionFlowAttribute” in operational contract to enable transaction flow.
[ServiceContract]
public interface IService
{

    [OperationContract]
    [TransactionFlow(TransactionFlowOption.Allowed)]
    int Add(int a, int b);

    [OperationContract]
    int Subtract(int a, int b);
}

Note: TransactionFlow can be enabled only at the operation level not at the service level.
TransactionFlowOption Binding configuration
NotAllowed transactionFlow="true"
or
transactionFlow="false"
Client cannot propagate its transaction to service even client has transaction
Allowed transactionFlow="true" Service will allow to flow client transaction.
It is not necessary that service to use client transaction.
Allowed transactionFlow="false" If service disallows at binding level, client also should disable at binding level else error will be occurred.
Mandatory transactionFlow="true" Both Service and client must use transaction aware binding
Mandatory transactionFlow="false" InvalidOperationException will be throw when serice binding disables at binding level.
FaultException will be thrown when client disable at its binding level.

what is the meaning of Transaction Protocols?

As a developer we no need to concern about transaction protocols and transaction manager used by WCF. WCF itself will take care of what kind of transaction protocols should be used for different situation. Basically there are three different kinds of transaction protocols used by WCF.

 

Advantage

  1. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
  2. WCF services provide better reliability and security in compared to ASMX web services.
  3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

0 comments:

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube