WCF Interview Question & Answer

13:45

Introduction

In this articales I give some WCf Interview Question & Answer.

What is service?

A service is a unit of functionality that exposed to the world.

What is WCF?

i) Its code name is "Indigo".
ii) WCF Stands for Windows Communication Foundation.
iii) Windows Communication Foundation is a programming model to create service oriented applications.
iv) It is a framework for building, developing, configuring and deploying interoperable distributed services.
v) WCF services provide better reliability and security in compared to ASMX web services.
vi) WCF = ASMX + .Net Remoting + WSE + Messaging + Enterprise Services

What are the transport schemes supported by WCF?

i) HTTP/HTTPS Ex: http://localhost:7000/MyService
ii) TCP(Transmission Control Protocol) Ex: net.tcp://localhost:7000/MyService
iii) IPC(Inter Process Communication) Ex: net.pipe://localhost/MyPipe
iv) Peer network
v) MSMQ(Microsoft Message Queuing) Ex: net.msmq://localhost/private/MyQueue
vi) Service bus Ex: sb://MyNamespace.servicebus.windows.net/

What are the types of Contract in WCF?

i)ServiceContract - Which services are exposed to the client.
ii)OperationContract - Which operations the client can perform on the service.
iii)DataContract – It describes the custom data type which is exposed to the client.
iv)MessageContract - WCF uses SOAP message for communication and 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.
v)FaultContract - 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.

What is the different types of hosting in WCF service?

There are mainly four types of hosting is WFC. i.e.
i) IIS hosting
ii) Self hosting
iii) Windows Activation Service
iv) Windows Service

What is Endpoint or ABC in WCF?

ABC or Endpoint = Address (A) + Binding (B) + Contract (C)
i) Address specifies where the services is hosted.
ii) Binding specifies how to access the hosted service. It specifies the transport, encoding, protocol etc.
iii) Contract specifies what type of data can be sent to or received from the service.
<system.serviceModel>
    <services>
        <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
        <endpoint
            address="http://localhost:7000/MyService/MyService.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 default endpoints?

If the service host does not define any endpoints neither in config nor programmatically, WCF will by default add endpoints to the service. These are called the default endpoints.

What is Address?

It is the url which specifies the location of the service. Client can use this url to connect to the service and invoke the service methods.

Example:

    http://localhost:7000/MyService/MyService.svc

What is binding?

Binding have the following characteristics:

i) Transport communicate between service and client by HTTP, TCP, MSMQ, NamedPipes etc. It is mandatory to define transport.

ii) Encoding encode the data before communicating it from one end to the other.

iii) Protocol defines the configurations like reliability, security, transaction, timouts, message size etc.

What are the types of bindings supported by WCF?

There are mainly 9 types of binding supported by WCF. They are following:
i) BasicHttpBinding: Basic Web service communication. No security by default.
ii) WSHttpBinding: Web services with WS-* support. Supports transactions.
ii) WSDualHttpBinding: Web services with duplex contract and transaction support.
iv) WSFederationHttpBinding: Web services with federated security. Supports transactions.
v) MsmqIntegrationBinding: Communication directly with MSMQ applications. Supports transactions.
vi) NetMsmqBinding: Communication between WCF applications by using queuing. Supports transactions.
vii) NetNamedPipeBinding: Communication between WCF applications on same computer. Supports duplex contracts and transactions.
viii) NetPeerTcpBinding: Communication between computers across peer-to-peer services. Supports duplex contracts.
ix) NetTcpBinding: Communication between WCF applications across computers. Supports duplex contracts and transactions.

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

How can you configure reliability using .config file?

<bindings>
    <netTcpBinding>
    <binding name="Reliable">
        <reliableSession enabled = "true"/>
    </binding>
    </netTcpBinding>
</bindings>

What is Message Exchange Pattern in WCF?

There are three way of communication between source and destination. These are below:
i) One-Way: It is one way communication. Source will send message to target, but target will not respond to the message.
i) Duplex/Callback: It is two way communication, both source and target can send and receive message simultaniouly.
iii) Request- Replay (default): 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.
Example:
public interface IMyDuplexServiceCallback
{
    [OperationContract(IsOneWay = true)]
    void Employee(string status);
}

[ServiceContract(CallbackContract = typeof(IMyDuplexServiceCallback))]
public interface IMyDuplexService
{
    [OperationContract(IsOneWay = true)] //One-Way
    void SaveEmployee();

    [OperationContract] //Request-Reply.
    string GetEmployee();
}

What are session modes in WCF?

There are three session modes supported by WCF:
i) Session.Allowed(default): Transport sessions are allowed, but not enforced. Service will behave as a per-session service only if the binding used maintains a transport-level session.
ii) Session.Required: Mandates the use of a transport-level session, but not necessarily an application-level session.
iii) Session.NotAllowed: Disallows the use of a transport-level session, which precludes an application-level session. Regardless of the service configuration, the service will always behave as a per-call service.
Example:
[ServiceContract(SessionMode = SessionMode.NotAllowed)]
interface IMyContract
{

}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract
{

}

How to manage WCF service instance creation?

There are three instance modes supported by WCF:
i) Per-Session (default): Service instance is created for each client. This service instance is disposed when the session ends.
ii) Per-Call: Service instance is created for each client request. This Service instance is disposed after response is sent back to client.
iii) Singleton: Service instance is created for all clients. This service instance is disposed when host shuts down.
Example:
[ServiceContract()]
public interface IMyService
{
    [OperationContract]
    int MyMethod();
}

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class MyService:IMyService
{
    public int MyMethod()
    {
        // Write functionality here
    }       
}

What is WCF throttling?

WCF throttling provides some properties that we can use to limit how many instances or sessions are created at the application level. Performance of the WCF service can be improved by creating proper instance.
WCF throttling provides the properties. i.e.
i) maxConcurrentCalls: Limits the total number of calls that can currently be in progress across all service instances. The default is 16.
ii) maxConcurrentInstances: Limits the number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue.
iii) maxConcurrentSessions: Limits the number of sessions a ServiceHost object can accept. It is a positive integer that is 10 by default.
Example:
<configuration>  
    <system.serviceModel>  
        <services>  
            <service>

            </service>  
        </services>  
        <behaviors>  
            <serviceBehaviors>  
                <behavior name="ServiceBehavior">  
                    <serviceThrottling maxConcurrentCalls="16" maxConcurrentSessions="100" maxConcurrentInstances="10" />  
                    <serviceMetadata httpGetEnabled="true" /> </behavior>  
            </serviceBehaviors>  
        </behaviors>  
    </system.serviceModel>  
</configuration>  

What is the difference between Web Service and WCF Service?

i) Web Service: It can be hosted in IIS.
i) WCF: It can be hosted in IIS, Self-hosting, WAS (windows activation service) and Windows service.
ii) Web Service: [WebService] attribute to the class to be exposed as a service.
ii) WCF: [ServiceContract] attribute to the class to be exposed as a service.
iii) Web Service:[WebMethod] attribute to the method exposed to client.
iii) WCF:[OperationContract] attribute to the method exposed to client.
iv) Web Service:It support One-way and Request- Response.
iv) WCF:It support One-Way, Request-Response and Duplex.
v) Web Service:System.Xml.serialization namespace is used.
v) WCF:System.Runtime.Serialization namespace is used.
vi) Web Service:Supports HTTP/HTTPS
vi) WCF:Supports HTTP/HTTPS, TCP, IPC, Peer network, MSMQ and Service bus

How can you implement operation overloading in WCF service?

We can implement operation overloading using “Name” property of OperationContract attribute.
Example:
[ServiceContract]
interface ICalculator
{
    [OperationContract(Name = "Add")]
    int Add(int arg1, int arg2);

    [OperationContract(Name = "Multiple")]
    double Add(double arg1, double arg2);
}

What is Known Types?

By default, you can not use a subclass of a data contract class instead of its base class. You need to explicitly tell WCF about the subclass using the KnownTypeAttribute.
Example:
[KnownType(typeof(Car))]
[KnownType(typeof(Truck))]
[DataContract]
public class Vehicle 
{
    //
}

[DataContract]
public class Car : Vehicle
{
    //
}

[DataContract]
public class Truck : Vehicle
{
    //
}

What is ServiceKnownType?

Instead of using the KnownType attribute on the base data contract, you can apply the ServiceKnownType attribute on a specific operation on the service side.
Example Using at Service Contract:
[ServiceKnownType(typeof(Car))]
[ServiceKnownType(typeof(Truck))]
[ServiceContract]
public Interface IVehicleService
{
     [OperationContract]
     Vehicle AddNewVehicle(Vehicle myVehicle);
 
     [OperationContract]
     bool UpdateVehicle(Vehicle myVehicle);  
}
Example Using at Operation Contract:
[ServiceContract]
public Interface IVehicleService
{
      [ServiceKnownType(typeof(Car))]
      [ServiceKnownType(typeof(Truck))]
      [OperationContract]
      Vehicle AddNewVehicle(Vehicle myVehicle);
 
      [OperationContract]
      bool UpdateVehicle(Vehicle myVehicle);  
}

What is WCF RIA service?

WCF RIA service is a framework to develop n-tier application for Rich Internet Application (RIA). It is mainly used in RIA applications like Silverlight, AJAX client, etc. It solves the major problem while developing business application like decoupling the resource access, application logic and presentation layer. WCF RIA service was introduced in Silverlight 4 with .net framework 4, and it can be developed using visual studio2010.
Main problem developer are facing while developing the n-tier RIA application will be coordinating the application logic between middle tier and presentation tier. This problem will be solved by using WCF RIA service, it will synchronize the code between middle and presentation tier.

What is RESTful WCF Service?

i) To use WCF as WCF Rest service you have to enable webHttpBindings.
ii) It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
iii) To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files.
iv) Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified.
v) It support XML, JSON and ATOM data format.

What is WCF Messaging Layer?

Messaging layer is composed of channels that processes a message in some way. Channels are the core abstraction for sending messages to and receiving messages from an Endpoint.
Message Structure: WCF uses messages to pass data or exchange information from one point to another. All messages are SOAP messages. The basic structures of a SOAP message are made up of three components. These are below:
i) SOAP Envelope: The SOAP envelope is a container for the two most important pieces of a SOAP message, the SOAP header and the SOAP body. A SOAP envelope contains several pieces of key information in the form of elements.
SOAP Envelope = Name + Namespace + Header + Body
ii) SOAP Header: Using a SOAP header, we can pass useful information about the services to the outer world if needed; it's just for information sharing. Any child elements of the header element are called "header blocks". This provides a mechanism for grouping logical data together.
iii) SOAP Body: This element contains the actual SOAP message for communication with the SOAP receiver; a message can contain zero or more bodies. Any information intended to be exchanged when the message reaches the intended destination goes in the message body.
We can achieve this using MessageContract. For Example:
[MessageContract]
public class Shape
{
    [MessageHeader]
    public string ID;

    [MessageBodyMember]
    public string Name;

    [MessageBodyMember]
    public int Age;
}

What is Information cards in WCF?

Information cards are analogous to real-world identity cards such as passports, driver's licenses, credit cards, and employee ID cards.
Benefits of adding Information Card:
i) Authentication
ii) Authorization
iii) Reduce IT pain
iv) Granting trust to domains
v) Helps in maintaining security

What is WCF transaction?

The four properties followed by a WCF transaction are the following:
i) Atomic: All the operations must act as a single indivisible operation at the completion of a transaction.
ii) Consistency:
Whatever may be the operation set, the system is always in a state of consistency, i.e., the outcome of the transaction is always as per the expectation.
iii) Isolation:
The intermediary state of system is not visible to any entities of the outer world till the transaction is completed.
iv) Durability:
Committed state is maintained regardless of any kind of failure (hardware, power outage, etc.)

Conclusion

Guys hope this will be helpfull.

You Might Also Like

0 comments