Tuesday, 4 February 2014

WCF Interview Questions



What is the difference between WCF and ASMX Web Services?
Simple and basic difference is that ASMX or ASP.NET web service is designed to send and receive messages using SOAP over HTTP only. While WCF can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, NamedPipes etc).

What are WCF Service Endpoints? Explain.
For Windows Communication Foundation services to be consumed, it’s necessary that it must be exposed; Clients need information about service to communicate with it. This is where service endpoints play their role.
A WCF service endpoint has three basic elements i.e. Address, Binding and Contract.
  1. Address: It defines "WHERE". Address is the URL that identifies the location of the service.
  2. Binding: It defines "HOW". Binding defines how the service can be accessed.
  3.  Contract: It defines "WHAT". Contract identifies what is exposed by the service.


What are the possible ways of hosting a WCF service? Explain.
For a Windows Communication Foundation service to host, we need at least a managed process, a ServiceHost instance and an Endpoint configured. Possible approaches for hosting a service are:
  1. Hosting in a Managed Application/ Self Hosting
    1. Console Application
    2. Windows Application
    3. Windows Service
  2. Hosting on Web Server
    1. IIS 6.0 (ASP.NET Application supports only HTTP)
    2. Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP, NamedPipes, MSMQ.

How we can achieve Operation Overloading while exposing WCF Services?
By default, WSDL doesn’t support operation overloading. Overloading behavior can be achieved by using "Name" property of OperationContract attribute.
 [ServiceContract]
interface IMyCalculator
{
   [OperationContract(Name = "SumInt")]
   int Sum(int arg1,int arg2);

   [OperationContract(Name = "SumDouble")]
   double Sum(double arg1,double arg2);
}
When the proxy will be generated for these operations, it will have 2 methods with different names i.e. SumInt and SumDouble.

What Message Exchange Patterns (MEPs) supported by WCF? Explain each of them briefly.
Request/Response: It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body.
One Way: In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. OneWay MEP will work in such scenarios. If we want queued message delivery, OneWay is the only available option.
Duplex: The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed.

What is DataContractSerializer and how it’s different from XmlSerializer?
Serialization is the process of converting an object instance to a portable and transferable format. So, whenever we are talking about web services, serialization is very important.
WCF has DataContractSerializer that is new in .NET 3.0 and uses opt-in approach as compared to XmlSerializer that uses opt-out. Opt-in means specify whatever we want to serialize while Opt-out means you don’t have to specify each and every property to serialize, specify only those you don’t want to serialize. DataContractSerializer is about 10% faster than XmlSerializer but it has almost no control over how the object will be serialized. If we wanted to have more control over how object should be serialized that XmlSerializer is a better choice.

How we can use MessageContract partially with DataContract for a service operation in WCF?
MessageContract must be used all or none. If we are using MessageContract into an operation signature, then we must use MessageContract as the only parameter type and as the return type of the operation.

Which standard binding could be used for a service that was designed to replace an existing ASMX web service?
The basicHttpBinding standard binding is designed to expose a service as if it is an ASMX/ASP.NET web service. This will enable us to support existing clients as applications are upgrade to WCF.

Please explain briefly different Instance Modes in WCF?
WCF will bind an incoming message request to a particular service instance, so the available modes are:
1)    Per Call: instance created for each call, most efficient in term of memory but need to maintain session.
2)    Per Session: Instance created for a complete session of a user. Session is maintained.
3)    Single: Only one instance created for all clients/users and shared among all. Least efficient in terms of memory.

Please explain different modes of security in WCF? Or Explain the difference between Transport and Message Level Security.
In Windows Communication Foundation, we can configure to use security at different levels:
a. Transport Level security: means providing security at the transport layer itself. When dealing with security at Transport level, we are concerned about integrity, privacy and authentication of message as it travels along the physical wire. It depends on the binding being used that how WCF makes it secure because most of the bindings have built-in security.
<netTcpBinding>
  <binding name="netTcpTransportBinding">
    <security mode="Transport">
      <Transport clientCredentialType="Windows" />
    </security>
  </binding>
</netTcpBinding>

b. Message Level Security: For Transport level security, we actually ensure the transport that is being used should be secured but in message level security, we actually secure the message. We encrypt the message before transporting it.
<wsHttpBinding>
  <binding name="wsHttpMessageBinding">
    <security mode="Message">
      <Message clientCredentialType="UserName" />
    </security>
  </binding>
</wsHttpBinding>

It totally depends upon the requirements but we can use a mixed security mode also as follows:
<basicHttpBinding>
  <binding name="basicHttp">
    <security mode="TransportWithMessageCredential">
      <Transport />
      <Message clientCredentialType="UserName" />
    </security>
  </binding>
</basicHttpBinding>


What are the various address formats in WCF?
1)    HTTP Address Format:–> http://localhost:
2)    TCP Address Format:–> net.tcp://localhost:
3)    MSMQ Address Format:–> net.msmq://localhost:

What are the types of binding available in WCF?
A binding is identified by the transport it supports and the encoding it uses. Transport may be HTTP, TCP etc. and encoding may be text, binary etc. The popular types of binding may be as below:
1)    BasicHttpBinding – Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.
2)    NetTcpBinding – Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.
3)    WSHttpBinding – Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.
4)    NetMsmqBinding – Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.
5)    NetPeerTcpBinding – Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.


What are the types of contract available in WCF?
The main contracts are:
1)    Service Contract: Describes what operations the client can perform.
2)    Operation Contract: Defines the method inside Interface of Service.
3)    Data Contract: Defines what data types are passed.
4)    Message Contract: Defines whether a service can interact directly with messages.


What is Proxy and how to generate proxy for WCF Services?
The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service’s contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.
Generating a Proxy class
1)    The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.
2)    Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.
SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs
When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:
SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs
A proxy is a class by which a service client can interact with the service.
By the use of proxy in the client application we are able to call the different methods exposed by the service

How to define a service as REST based service in WCF?
WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding. The below code shows how to expose a RESTful service:
[ServiceContract]
interface IStock
{
  [OperationContract]
  [WebGet]
  int GetStock(string StockId);
}
By adding the WebGet Attribute, we can define a service as REST based service that can be accessible using HTTP GET operation.

What are the advantages of hosting WCF Services in IIS as compared to self-hosting?
Automatic activation: IIS provides automatic activation that means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in case of self-hosting the service should always be running.
Process recycling: If IIS finds that a service is not healthy that means if it has memory leaks etc, IIS recycles the process. Ok let us try to understand what is recycling in IIS process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, process stops and you lose all information. IIS also restarts the worker process. By default, the worker process is recycled at around 120 minutes. So why does IIS recycle. By restarting the worker process it ensures any bad code or memory leak do not cause issue to the whole system.
Self-hosting gives you full control like when to start a service host, stop and so on. But, you need to recycle the service and have to programmatically handle all the required things to make your service to work in critical errors. Sometimes, it may lead to server crash.

What is poison message?
A message is sent to a receiver that is malformed or causes some kind of exception and cannot be processed by a receiver. This problem is known as poison message and it occurs while the message is in the queue and causing problems, no other messages can get processed, so in essence the poison message logs up the queue.

What is dead letters?
A message has a time-to-live that expires before the message is processed. This problem is called as dead letters. In WCF and MSMQ, dead letter processing is controlled by the client-side of the WCF conversation. The client or sender specifies the time-to-live for the message and also specifies where the dead letter message is sent to.

Why WCF Services are considered as loosely coupled?
WCF Services are considered as loosely coupled because WCF services are not tightly bound to a particular protocol, encoding format, or hosting environment. All of these are configurable. At the time of designing WCF services, we don’t have to worry about what protocol, encoding format, or hosting environment to use to expose the service. We can worry about all these at the time of deployment.

What is the role of WSDL in WCF?  OR What is WSDL?
WSDL stands for Web Service Description Language. The WCF service exposes the WSDL document for the clients, to generate proxies and the configuration file. The WSDL file provides the following information for the consumers of the WCF service:
1)    Provides the information about the service contract and operations available.
2)    Provides the information about all the end points exposed by the WCF service.
3)    Provides the information about the messages and types that can be exchanged between the client and the WCF service.
4)    WSDL also provides any information about the policies used.



Can you apply ServiceContract attribute to a class rather than an interface in WCF?
Yes, a ServiceContract attribute can be applied either to a class or an interface, but defining service contracts using interfaces rather classes has the following benefits:
1)    Defining service contracts using interfaces, removes coupling to service implementation. Later the implementation can be changed at will without affecting the clients.
2)    Defining service contracts using interfaces, also allows a service to implement more than 1 contract.

What is the purpose of MessageParameter attribute in WCF?
MessageParameter attribute is used to control the parameter and returned object names from a service operation. Consider the example below. On the service side, the method parameter name in SaveCustomer([MessageParameter(Name = "Customer")] Customer cust) is cust. If we don’t use MessageParameter attribute, then "cust" is what is exposed as parameter name to the client, which is not very proffesional. So we are using MessageParameter attribute to expose the method parameter name as Cutomer.




What are the different options available to serialize complex types that are sent and received between clients and services in WCF?
Data contract is the preferred way to serialize complex types in WCF:
1)   Serializable types - Use the Serializable attribute on the type that you want to serialize.
2)    Data contracts - Use DataContract attribute on the type and DataMember attribute on every member of the type, which you want to serialize. You can apply DataMember attribute either on a filed or a property.
3)   Known types - Use Known types to enable polymorphic behavior in service contracts.
4)   IXmlSerializable - IXmlSerializable types provide XSD schema to Web Services Description Language (WSDL) and metadata exchange (MEX).

What is the disadvantage of using Serializable attribute to serialize a complex type that is sent and received between clients and services in WCF?
When we decorate a class with Serializable attribute, all the fields of the class are serialized regardless of the accessibility. We don’t have control on what to serialize and what not to serialize. We also will not have any control over naming conventions or data types.


What is the preferred way for serializing complex types in WCF?
The preferred way for serializing complex types in WCF is to use data contracts. Using Data Contracts provides us with the following advantages:
1)    Using DataMember attribute, you can control which members of the class to serialize.
2)    You can also control the order in which members are serialized using Order parameter of the DataMember attribute.
3)    You can also provide explicit Name to the serialized members using Name parameter of the DataMember attribute.
4)    You can also specify if a member is required or optional using IsRequired parameter of the DataMember attribute.
Consider the example below which uses Name, IsRequired and Order parameters of the DataMember attribute to serialize CustomerId property. By the way DataMember attribute can be used with either fields or properties. If you donot specify the order in which members are serialized, then by default alphabetical ordering is done by the DataContractSerializer.    




Explain the significance of MessageContract attributes OR Why and when do you use MessageContract attribute?
There are several advantages of using MessageContract attribute in WCF. MessageContract attribute can be used for:
1)    Adding custom headers to the message.
2)    Controlling message wrapping.
3)    Controlling signing and encryption of messages.
MessageContract attribute provides us with greater control over message headers and body elements. MessageContract attribute converts a type to a SOAP message. The example below shows how to use IsWrapped and ProtectionLevel parameters of MessageContract attribute. You may also set an explicit Name and Namespace.




What is WS-Policy? OR What is Web Services Policy?
Web Services Policy or WS-Policy is an interoperable standard for describing policies that influence communication with the clients. Usually WS-Policy is included in the WSDL contract exposed by the WCF service, although it is optional.


What is the use of WS-Policy?
WS-Policy is generally used for:
1)    Describing protocols for accessing operations
2)    Security
3)    Reliable messaging
4)    Transactions
5)    Message encoding (Message Transmission Optimization Mechanism [MTOM])
6)    Other protocols
You can specify the above settings in WSDL directly without a policy section, but the disadvantage is that, once published, the WSDL contract is final. If the clients has to communicate with a WCF service that has changed the settings in the WSDL, the clients need to rebuild the proxy and configuration or at least the changes to the WSDL contract must support backward compatibility.
The advantage of using WS-Policy is that it can change over time, and the clients can discover the changed policy to communicate via metadata exchange. But keep in mind that, you can only change the policy safely if clients are positioned to handle dynamic changes.


Are WCF Contracts versions tolerant?
Yes, WCF contracts are version tolerant by default. Service contracts, data contracts, and message contracts forgive missing and non-required data. They also ignore any superfluous or additional data sent by the client to the service. The DataContractSerializer provides tolerance. Reasonable changes can be made without impacting existing clients.
The following table summarizes the changes to a service contract and impact on existing clients.



What happens if there is an unhandled exception in WCF?
If there is an unhandled exception in WCF, the service model returns a general SOAP fault, that does not include any exception specific details by default. However, you can include exception details in SOAP faults, using IncludeExceptionDetailsInFaults attribute. If IncludeExceptionDetailsInFaults is enabled, exception details including stack trace are included in the generated SOAP fault. IncludeExceptionDetailsInFaults should be enabled for debugging purposes only. Sending stack trace details is risky.


2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I do have 10 years of experience i too read WCF and C# interview questions from skillgun . Most of the c# interview questions and answers written by the author is very much useful for clearing experienced as well as c# interview questions and answers for freshers . WCF section is having relatively average questions which you can find in wcf interview questions and answers

    ReplyDelete