Tuesday, 14 May 2013

WCF Interview Questions and Answer

WCF Interview Questions

What is WCF?
WCF stands for Windows Communication Foundation (WCF) and is considered as the Microsoft Service-Oriented Architecture (SOA) platform for building distributed and interoperable applications. WCF unifies ASMX, Remoting, and Enterprise Services stacks and provides a single programming model. WCF services are interoperable and supports all the core Web services standards. WCF services also provide extension points to quickly adapt to new protocols and updates and integrates very easily with the earlier microsoft technologies like Enterprise Services, COM and MSMQ.

What is the version of the .NET framework in which WCF is released?
WCF - Windows Communication Foundation is released as part of .NET Framework 3.0. WPF (Windows Presentation Foundation), WF (Workflow Foundation) and Card Space are also part of .NET Framework 3.0.

What is the advantage of using WCF over other distributed programming models like Web Services(ASMX), .NET Remoting, Enterprise Services stack etc.?
To understand the advantage of using WCF over other distributed programming models like Web Services(ASMX), .NET Remoting, Enterprise Services stack etc, let's consider the following scenario. We have developed an application using web services. As we know web services use HTTP protocl and XML SOAP formatted messages, they are good for developing interoperable applications in a heterogeniuos environment. We have a new client. Our new client is using .NET and he wants binary formmatted messages over TCP protocol, because interoperability is not a concern and binary formmatted messages over TCP protocol are much faster than XML SOAP formmatted messages over HTTP. To satisfy the requirement of this client, now we cannot use our existing web service. So, we have to develop a brand new remoting application from the scratch. The business functionality is the same in web services and remoting application. Since our different clients have different requirements, we ended up creating the same business application using web services and remoting technologies. This approach has several disadvantages as listed below.
1. Developers have to be familiar with two different technologies (Web Services and Remoting).
2. We end up creating duplicate business applications with different technologies which also leads to maintainance overhead.

On the other hand WCF unifies Web Services, .NET Remoting, and Enterprise Services stacks under one roof. For the same requirement that we have seen untill now, we just create one application and expose multiple end points to satisfy the requirements of multiple clients. In WCF configuration drives protocol choices, messaging formats, process allocation, etc. WCF services are loosely coupled, meaning that a WCF service is not bound to a particular protocol, encoding format, or hosting environment. Everything is configurable. 

Why are 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 donot 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 are the 3 things that a WCF Services end point must have? 
What are the ABC of a WCF service?
Address - The address where the WCF Service is hosted.
Binding - The binding that decides the protocol, message encoding and security to use. Binding also decides whether to use reliable messaging and transaction support.
Contract - The service contract defines what service operations are available to the client for consumption.

So the Address(A), Binding(B) and Contract(C) are called as the ABC of the service end point.

What is the role of WSDL in WCF?
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.

What is the tool that a client application can use to generate the proxy for a WCF service?
Service Utility (svcutil.exe) can be used by the clients to generate the proxy and configuration file. For the client to be able to generate proxies, the service should enable metadata exchange. 

Define Service Contracts and Operation Contracts in WCF?
1. Service Contract - An interface that exposes the service operations is usually decorated with the service contract attribute. Always provide meaningful Namespace and Name to a service contract as shown in theexample below.

2. Operation Contract - All methods in a service contract should have OperationContract attribute. You can also provide explicit Name, Action and ReplyAction as shown in the example below.

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

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 donot 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?
The following are the different options available to serialize complex types that are exchanged between clients and services in WCF. These options have their own advantages and disadvanatages. Data contracts is thepreferred way to serialize complex types in WCF.
1. Serializable types - Us 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, that 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 donot 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.

What is the best way to serialize Polymorphic Types in WCF?
The best way to serialize Polymorphic Types in WCF is to use KnownType attribute on the parent type as shown in the example below. CorporateCustomer and PremiumCustomer classes inherit from Customer class,and hence we can associate CorporateCustomer and PremiumCustomer types as known types in 3 different ways depending on the project requirement.

1. Associate known types to the base types themselves.
2. Associate known types to particular operations.
3. Associate known types to the service contract as a whole.

In Example 1, we are associating known types, CorporateCustomer and PremiumCustomer to the base type, Customer.

In Example 2, we are associating known type, CorporateCustomer on SaveCorporateCustomer(Customer customer) and GetCorporateCustomer(int CustomerId) operations using ServiceKnownType attribute.

In Example 3, we are associating known types, CorporateCustomer and PremiumCustomer to the service contract ICustomerService as a whole.

It is also possible to specify known types in a configuration file rather than in code. Example 4 shows how to specify known types in configuration.file.

Explain the significane of MessageContract attribute?
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. Controling message wrapping.
3. Controling 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.

MessageContract attribute is supported by MessageHeader attribute and MessageBodyMember attribute. You can apply MessageHeader attribute to fields or properties of message contract. This is a simple technique for creating custom headers.You can provide Name, Namespace and ProtectionLevel. You may also set SOAP protocol settings like Relay, Actor, MustUnderstand.

MessageBodyMember attribute can also be Applied to fields or properties of message contract.Can have several body elements. This is equivalent to multiple parameters in operation and this is the only way to return multiple complex types. It is suggested as a good practice to always supply Order. You can also set Name, Namespace, ProtectionLevel. The example below shows how to use MessageHeader and MessageBodyMember attributes.

What is WS-Policy?
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 atleast 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 version 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 is IExtensibleDataObject?
What is the advantage and disadvantage of implementing IExtensibleDataObject?

WCF guidelines recommend enhancing all data contracts with support of IExtensibleDataObject interface, to preserve unexpected data from clients. During deserialization, superfluous data is placed in a dictionary on the service side and during serialization, the same data is written as XML as it was originally provided by the client. This is very useful to preserve data from version 2.0 services at a version 1.0 client. It is also useful in case where downstream calls from version 2.0 services go to other services handling version 1.0. 
However, there is also a disadvantage of implementing IExtensibleDataObject. It carries risks of denial of service (DoS) and unnecessary use of server resources.

We can turn on and off, the support for IExtensibleDataObject either in code declaratively using attributes or in the configuration file as shown below.


Disabling support for IExtensibleDataObject in Code using attributes
Disabling support for IExtensibleDataObject in configuration

What are SOAP Faults in WCF?

Common language runtime (CLR) exceptions do not flow across service boundaries. At the maximum, a CLR exceptions may propagate up to the service tier from business components. Unhandled CLR exceptions reach the service channel and are serialized as SOAP faults before reporting to clients. An unhandled CLR exception will fault the service channel, taking any existing sessions with it. That is why it is very importatnt to convert the CLR exceptions into SOAP faults. Where possible, throw fault exceptions

SOAP faults are standards based and interoperable. There are 2 formats used by SOAP faults, SOAP 1.1 and SOAP 1.2. SOAP format depends on the binding used.

What happens if there is an unhandled exception in WCF?

If there is an unhandled exception in WCF, the 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.

What are the 2 ways to enable IncludeExceptionDetailsInFaults for a WCF service?

Either programatically or thru configuration. 

To enable thru code use ServiceBehaviorAttribute as shown below:


public class PragimService : IPragimService

To enable using configuration use servicedebug element as shown below

What are bindings in WCF?
Bindings in WCF define the configuration of communication channel between clients and services. Binding specifies 
1. Transport Protocol
2. Message encoding
3. Security Mechanism
4. Reliable Messaging
5. Transactions Support

What are different Transport protocols available in WCF?
1. TCP
3. Named Pipes

What message encoding formats are available in WCF?
1. Text - For interoperability
2. MTOM (Transmission Optimization Mechanism) - For transfering large objects
3. Binary - For speed

What are the 2 ways available for configuring bindings in WCF?
1. Declaratively using a configuration file
2. Programatically in the code.

Using configuration file has several advantages.

List a few standard bindings available in WCF?
1. BasicHttpBinding
2. NetPeerTcpBinding
3. WSFederationHttpBinding
4. NetNamedPipeBinding
5. WSHttpBinding
6. WSDualHttpBinding
7. NetTcpBinding
8. NetMsmqBinding
9. MsmqIntegrationBinding

Can you create a customized binding in WCF?
Yes, bindings in WCF are completely extensible and we can create a customized one. 

Can you overload methods in a WCF service?
Yes, it is possible to overload methods in a WCF service, but the names of the exposed operation contracts must be unique. To achieve this we can use the Name property of OperationContractAttribute. Let us understand this with an example.

If I have the WCF service designed as shown below, the service compiles without any issues. 
When we try to run the service, we will get InvalidOperationException.

What are the different message exchanging patterns available in WCF?
There are 3 main different message exchanging patterns available in WCF.
1. Request-Reply - In the request-reply pattern, a client application sends a message to a WCF service and then waits for a reply. This is the classic and most commonly used message exchange pattern in WCF.
2. One-Way - In a one way message exchange pattern no response is sent back, even if there is an exception. In the one-way message exchange pattern, a client application sends a message to a WCF service but the service does not send a reply message to the client. You can use this pattern when a client requests the service take an action but does not need to wait for a reply.
3. Duplex - In the request/reply and one-way message exchange patterns, only the client can initiate communication. In the duplex pattern, both the client and the service can initiate communication. The client calls a method of the service. The service can then use a client callback to call a method in the client. You can use this pattern when you want the service to send a notification or alert to the client after the client has called the service.

What is the default message exchange pattern used in WCF?

How do you setup a one way operation?
Set OperationContractAttribute's IsOneWay property to true. An example is shown below.

What is MTOM?
MTOM stands for Message Transmission Optimization Mechanism and is an Interoperable standard that reduces the overhead of large binary data transfera. Removes bloat and processing overhead of base64 encoded data. Improves overall message transfer performance. 

To correct this we can use the Name property of OperationContractAttribute as shown below. After this change, the service works fine both at compile and runtime.

Post a Comment