Friday 27 September 2013

WCF(Window Communication Foundation) Interview Question & Answers


1. What is WCF ?
  • Stands for Windows Communication Foundation.
  • Its code name is “Indigo”.
  • It is a framework for building, configuring and deploying interoperable distributed services.
  • It enables you to write more secure flexible services without any code change (using configuration).
  • It also provide built-in support for logging. You can enable/disable logging using configuration.
WCF = Web Service + Remoting + MSMQ + COM+
(or)
WCF = ASMX + .Net Remoting + WSE + Messaging + Enterprise Services

2. What is Contract ? What are the types of Contract ?

It is the agreement between client and service which specifies:

  • [ServiceContract] - which services are exposed to the client.
  • [OperationContract] - which operations the client can perform on the service.
  • [DataContract] – which data types are passed to and from the service.
  • [MessageContract] - allow the service to interact directly with messages. Message contracts can be typed or untyped and are useful in interoperability cases when another party has alreadydictated some explicit (typically proprietary) message format.
  • [FaultContract] -which errors are raised by the service and how the service handles andpropagates errors to its clients.

3. Difference between WCF and ASP.NET Web Service

Here are the 10 important differences between WCF Services and ASP.NET Web Services:

4. What are the transport schemes supported by WCF ? Give example of address for each scheme.

Following are the transport schemes supported by WCF:


  • HTTP/HTTPS - http://localhost:8001/MyService
  • TCP - net.tcp://localhost:8002/MyService
  • IPC - net.pipe://localhost/MyPipe
  • Peer network
  • MSMQ - net.msmq://localhost/private/MyQueue
  • Service bus - sb://MyNamespace.servicebus.windows.net/

5. What is binding ?

A binding is the set of configurations regarding the transport protocol, message encoding, communication pattern, reliability, security, transaction propagation, and interoperability.


6. What are the types of bindings supported by WCF ? What are their advantages and disadvantages ?

BindingFeatureSuitable ForTransportMessage encodingSecurity ModeResource ManagerTransaction Flow
BasicHttpBindingNot secure by default.Communication with WS-Basic Profile conformant Web Services like ASMX.HTTPTextNoneXX
WSHttpBindingSecure, Interoperable.Non-duplex service contracts.HTTPTextMessageDisabledWS-Atomic
WSDualHttpBindingSecure, Interoperable.Duplex service contracts or communication through SOAP intermediaries.HTTPTextMessageEnabledWS-Atomic transaction
WSFederationHttpBindingSecure, Interoperable.Supports the WS-Federation protocol, enabling organizations that are in a federation to efficiently authenticate and authorize users.HTTPTextMessageDisabledWS-Atomic transaction
NetTcpBindingSecure, Optimized.Cross-machine communication between WCF applications.TCPBinaryTransportDisabledOle transaction.
NetPeerTcpBindingSecure.Multi-machine communication.P2PBinaryTransportXX
NetNamedPipesBindingSecure, Reliable, Optimized.On-machine communication between WCF applications.Named PipesBinaryTransportXOle transaction.
NetMsmqBindingCross-machine communication between WCF applications.MSMQBinaryMessageXX
MsmqIntegrationBindingDoes not use a WCF message encoding – instead it lets you choose a pre-WCF serialization format.Cross-machine communication between a WCF application and existing MSMQ applications.MSMQPre-WCF formatTransportXX

7. What is Endpoint in WCF ?

Endpoint = Address (A) + Binding (B) + Contract (C)
Address specifies where the services is hosted.
Binding specifies how to access the hosted service. It specifies the transport, encoding, protocol etc.
Contract specifies what type of data can be sent to or received from the service.
Eg:
<endpoint name="BasicHttpGreetingService" address="http://localhost:5487/MyService/GreetingService.svc" binding="basicHttpBinding" contract="MyNamespace.MyService.IGreetingService" />

8. Explain Address in detail ?

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.

Eg: http://localhost:5487/MyService/GreetingService.svc

9.  Explain Binding in detail ?

It specifies how to access the hosted service. There are following characteristics of binding:
Transport defines the communication protocol to be used to communicate between service and client. It may be HTTP, TCP, MSMQ, NamedPipes etc. It is mandatory to define transport.
Encoding defines the technique used to encode the data before communicating it from one end to the other.
Protocol defines the configurations like reliability, security, transaction, timouts, message size etc.

10. What is binding configuration ?

You can customize the binding used by endpoint using config file. For example, you can enable/disable transaction for the binding used by endpoint. All you need is to configure binding element in config file similar as below:
<bindings>
  <netTcpBinding>
    <binding name = "TransactionalTCP" transactionFlow = "true" />
  </netTcpBinding>
</bindings>

11. What is default endpoints ?

If the service host does not define any endpoints (neither in config nor programmatically) but does provide at least one base address, WCF will by default add endpoints to the service. These are called the default endpoints. WCF will add an endpoint per base address per contract, using the base address as the endpoint’s address. WCF will infer the binding from the scheme of the base address. For HTTP, WCF will use the basic binding. Note that the default bindings will affect the default endpoints. WCF will also name the endpoint by concatenating the binding name and the contract name.

12. How can we enable/disable metadata publishing of our WCF service ?

You can enable enable meta data publishing for a WCF service two ways:
  • Configure metadata publishing for a service that uses default endpoints. Specify the ServiceMetadataBehavior in the configuration file but do not specify any endpoints.
<configuration>
 <system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="CustomServiceBehavior">
         <serviceMetadata httpGetEnabled="True" />
         <serviceDebug includeExceptionDetailInFaults="False" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>
</configuration>
  • Configure metadata publishing for a service that uses explicit endpoints. Specify the ServiceMetadataBehavior in the configuration file and a mex endpoint.
<configuration>
 <system.serviceModel>
   <services>
     <service name="MyNamespace.MyService.GreetingService" behaviorConfiguration="CustomServiceBehavior">
       <endpoint address="" binding="wsHttpBinding" contract="MyNamespace.MyService.IGreetingService" />
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
     </service>
   </services> 
   <behaviors>
     <serviceBehaviors>
       <behavior name="CustomServiceBehavior">
         <serviceMetadata httpGetEnabled="True" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>
</configuration>
Supported bindings for mex endpoint are mexHttpBindingmexHttpsBindingmexNamedPipeBinding andmexTcpBinding.

13. How can you generate proxy class and configuration file for WCF service ?

WCF provides an utility svcutil.exe which can be used to generate proxy class and configuration file. Eg:
SvcUtil http://localhost:8002/MyService/ /out:Proxy.cs /noconfig

14. Is there any tool provided by Microsoft for editing configuration file ?

Yes. Microsoft provides an utility “SvcConfigEditor.exe” that can edit any configuration file.

15. How can you test your new WCF service without writing any client application ?

Microsoft provides a tool which can be used to test any WCF service. To use this tool, open visual studio command prompt and execute the command “wcftestclient.exe“. It will open a window where you can add many WCF services and test. You can also provide values for input parameters of WCF methods.

16. Which bindings support reliability and message ordering ?

Binding nameSupports
reliability
Default
reliability
Supports ordered
delivery
Default Ordered
delivery
BasicHttpBindingNoN/ANoN/A
NetTcpBindingYesOffYesOn
NetNamedPipeBindingNoN/A(On)YesN/A(On)
WSHttpBindingYesOffYesOn
NetMsmqBindingNoN/ANoN/A

17. How can you configure reliability using .config file ?

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

18. How to create a service contract and operation contract ? Can you give an example ?

We can create a contract using an interface by applying [ServiceContract] and [OperationContract] attributes on Interface and Methods respectively.
[ServiceContract]
public interface IGreetingService
{
    [OperationContract]
    string GreetMe(string userName);
}

public class GreetingService : IGreetingService
{
    public string GreetMe(string userName)
    {
        return string.Format("Welcome {0}", userName);
    }
}
If we do not want to create interface then we can apply the attributes on a class itself.
[ServiceContract]
public class GreetingService
{
    [OperationContract]
    public string GreetMe(string userName)
    {
        return string.Format("Welcome {0}", userName);
    }
}

19 . Can you give an example of DataContract ?

[DataContract]
public enum Color
{
  [EnumMember]
  Red,

  [EnumMember]
  Green,

  [EnumMember]
  Blue
}
[DataContract]
public class Shape
{
  [DataMember]
  public string Name { get; set; }

  [DataMember]
  public Color FillColor { get; set; }

  [DataMember]
  public double Area { get; set; }
}

20. What is MessageContract ? Can you give an example ?

WCF uses SOAP messages to transfer information from client to server and vice-versa. It converts data contract to SOAP messages. SOAP message contains Envelope, Header and Body. SOAP envelope contains name, namespace, header and body element. SOAP Header contains important information which are related to communication but not directly related to message. SOAP body contains information which is used by the target.

SOAP Envelope = Name + Namespace  + Header + Body
However there are some cases when you want to have control over the SOAP messages. You can achieve this using MessageContract.

[MessageContract]
public class Shape
{
    [MessageHeader]
    public string ID;
    [MessageBodyMember]
    public string Name;
    [MessageBodyMember]
    public double Area;
}
In above example, ID will be added as header, Name and Area as body in SOAP envelope.
When you use MessageContract then you have control over the SOAP message. However some restrictions are imposed as below:
  • You can have only one parameter for a service operation if you are using MessageContract.
  • You can return either void or MessageContract type from service operation. Service operation can not return DataContract type.
  • Service operation can accept and return only MessageContract type.
Some important points about MessageContract:
  • You can mention the MessageHeader or MessageBodyMember to be signed or Encrypted using ProtectionLevel property.
  • The order of the body elements are alphabetical by default. But you can control the order, using Order property in the MessageBody attribute.

21. What is FaultContract ?

In most of the cases you would like to convey the details about any error which occurred at service end. By default, WCF exceptions do not reach client. However you can use FaultContract to send the exception details to client.

[DataContract()]
public class CustomError
{
  [DataMember()]
  public string ErrorCode;
  [DataMember()]
  public string Title;
  [DataMember()]
  public string ErrorDetail;
}

[ServiceContract()]
public interface IGreetingService
{
  [OperationContract()]
  [FaultContract(typeof(CustomError))]
  string Greet(string userName);
}

public class GreetingService : IGreetingService
{
  public string Greet(string userName)
  {
    if (string.IsNullOrWhiteSpace(userName))
    {
        var exception = new CustomError()
        {
            ErrorCode = "401",
            Title = "Null or empty",
            ErrorDetail = "Null or empty user name has been provided"
        };
        throw new FaultException<CustomError>(exception, "Reason : Input error");
    }
    return string.Format("Welcome {0}", userName);
  }
}

22. What are session modes in WCF ? How can you make a service as sessionful ?

ServiceContract attribute offers the property SessionMode which is used to specify the session mode. There are three session modes supported by WCF:
  • 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.
  • Session.Required: Mandates the use of a transport-level session, but not necessarily an application-level session.
  • 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. 
[ServiceContract(SessionMode = SessionMode.NotAllowed)]
interface IMyContract
{...}

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



No comments:

Post a Comment