WCF Exclusive Interview Questions and Answers (54) - Page 1

  • A joint initiative from DotNetFunda.Com and Questpond.
  • A one stop place on the internet to get trusted and proven Interview Questions (based on more than a decade of experience in this field) to ensure the success of the candidates.
  • You will find almost all Interview questions from Questpond here and this list is growing day by day with all latest and updated interview questions.

54 records found.

Get 650+ Questpond's Interview videos on discount

What is WCF?

Answer: -

First let us give a short answer to this: - “WCF (Indigo was the code name for WCF) is a unification of .NET framework communication technologies “.WCF is a unification technology, which unites the following technologies:-
• NET remoting
• Web services
• COM+.
Below figure depicts WCF fundamentals pictorially.

 WCF Components

What is .NET 3.0?

In one simple equation .NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows Presentation Foundation + Windows Workflow Foundation + Windows Card Space.

What is Windows Card Space?

Answer: -
It was previously known by its codename Info Card. It is a framework by Microsoft, which securely stores digital identities of a user and provides a unified interface to choose the identity for a particular transaction, such as logging in to a website. Windows Card Space is a central part of Microsoft’s effort to create an identity met system, or a unified, secure and interoperable identity layer for the internet.

What are the important principles of SOA (Service oriented Architecture)?

Answer: -

WCF is based on SOA. All big companies are playing big bets on SOA. So how can Microsoft remain behind? So in order to implement SOA architecture easily you need to use WCF.
SOA is based on four important concepts:-

• Boundaries are well defined

In SOA, everything is formalized. The client who is consuming the service does not need to know how the implementation of the service is done. If you look at some old methodologies of communication like DCOM. Any changes at server level the client also has to change. Therefore, the server and client implementation was so much bound that changes need to be done at all places. In SOA, the rule is if you do enhancement you do not need to change anything at the client. SOA based application only understands that there is an end point, contract, and bindings.

Note: - Just to clarify shortly about end point and contract. Any SOA service is exposed through an end point. End point defines three important aspects What, Where and How. We will understand more details of the same in the later questions.

• Services evolve

Change is the law of nature and services will evolve. In SOA, services can be versioned and you can host those services in new ends. For instance, you have a service called as “Search Tickets (Ticket Number) “which gives details based on Ticket Number and its exposed on end point “ep1”. Tomorrow you want make your Search Tickets service more useful by also providing an extra option of allowing him to search by passenger name. Therefore, you just declare a new end “ep2” with service “Search Tickets (Ticket Number, Passenger Name)”. So the client who is consuming the service at end ep1 continues and at the other end, we have evolved our service by adding new ends ep2.

• Services share only schemas and contracts

Services use Schemas to represent data and contracts to understand behavior. They do not use language dependent types or classes in order to understand data and behavior. XML is used to define schemas and contracts. Due to this, there is not heavy coupling between environments.

• Service compatibility is policy based

Policy describes the capabilities of the system. Depending on policies, the service can degrade to match the service for the client. For instance your service needs to be hosted for two types of client one which uses Remoting as the communication methodology while other client uses DCOM. An ideal SOA service can cater to both of them according to there communication policies.

Note: - Many people assume Web services are the base for SOA. The answer is 50 % right. What web services lack is the policy based Service compatibility. If you host a web service it can only serve with HTTP communication channel and SOAP message. Any other type of client trying to communicate he will not degrade it self. This is what is provided by WCF. You can host the service in one or more mode. For instance you can host a WCF service using remoting and ASMX.

What are ends, contracts, address and bindings?

Answer: -
The above terminologies are the core on which SOA stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things where, what and how:-

• Contract (What)
Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method.

• Address (Where)
An Address indicates where we can find this service. Address is a URL, which points to the location of the service.

• Binding (How)
Bindings determine how this end can be accessed. It determines how communications is done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created.
Below figure, show the three main components of end. You can see the stock ticker is the service class, which has an end hosted on www.soa.com with HTTP and TCP binding support and using Stock Ticker interface type.

Figure 2: - Endpoint Architecture

Note: - You can also remember the end point by ABC where A stands for Address, B for bindings and C for Contract.

Which specifications does WCF follow?

Answer: -
WCF supports specifications defined by WS-* specifications. WS-* specifications are defined together by Microsoft, IBM, SUN and many other big companies so that they can expose there service through a common protocol. WCF supports all specifications defined we will understand them one by one.

• Messaging (WS-Addressing):-
SOAP is the fundamental protocol for web services. WS Addressing defines some extra additions to SOAP headers, which makes SOAP free from underlying transport protocol. One of the good things about Message transmission is MTOM, also termed as Message Transmission Optimization Mechanism. They optimize transmission format for SOAP messages in XML-Binary formant using XML optimized packaging (XOP). Because the data will sent in binary and optimized format, it will give us huge performance gain.

• Security (WS-Security, WS-Trust, and WS-Secure Conversation): -
All the three WS- define authentication, security, data integrity and privacy features for a service.

• Reliability (WS-Reliable Messaging): - This specification ensures end-to-end communication when we want SOAP messages to be traversed back and forth many times.

• Transactions (WS-Coordination and WS-Atomic Transaction): - These two specifications enable transaction with SOAP messages.

• Metadata (WS-Policy and WS-Metadata exchange): - WSDL is a implementation of WS-Metadata Exchange protocol. WS-Policy defines more dynamic features of a service, which cannot be expressed by WSDL.
We have stressed on the WS-* specification as it is a specification which a service has to follow to be compatible with other languages. Because WCF follows WS-* specifications other languages like JAVA , C++ can also exploit features like Messaging , Security , Reliability and transactions written in C# or VB.NET. This is the biggest achievement of WCF to integrate the above features with other languages. 

Note: - During interview the interviewer expects that you know what WS-* specification are supported by WCF and its advantages with respect to interacting with other languages.

What are the main components of WCF?

Answer: -
We need to define three main components in WCF:-
• Service class.
• Hosting environment
• End point

What are the various ways of hosting a WCF service?

Answer: -
There are three major ways to host a WCF service:-
• Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
• Host in application domain or process provided by IIS Server.
• Host in Application domain and process provided by WAS (Windows Activation Service) Server.

What are the major differences between services and Web services? OR What is the difference WCF and Web services?

Answer: -
Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type. Second web services are not flexible. However, Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

What are different bindings supported by WCF?

Answer: -
WCF includes predefined bindings. They cover most of bindings widely needed in day-to-day application. However, just incase you find that you need to define something custom WCF does not stop you. So let us try to understand what each binding provides.

BasicHttpBinding: - This binding is used when we need to use SOAP over HTTP. This binding can also be configured to be used as HTTPS. It can be also configured to send data in plain text or in optimized form like MTOM.

WsHttpBinding: - It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with it also supports reliable message transfer, security and transaction. WS-Reliable Messaging, security with WS-Security, and transactions with WS-Atomic Transaction supports reliable message.

NetTcpBinding: - This binding sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. The biggest disadvantage of NetTcpBinding is that both server and client should be also made in .NET language.

NetNamedPipesBinding:-Ths binding Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.

Note: - An interprocess control (IPC) protocol is used for exchanging information between two applications, possibly running on different computers in a network. The difference between Named pipes and TCP is that named pipes have good performance in terms of communication with in processes. But when it comes to communicate across network TCP holds the best choice. So if you are using WCF to communicate with process it’s the best choice to use in terms for performance. Named pipes do not perform when the traffic is heavy as compared to TCPIP.

NetMsmqBinding: - This binding sends binary-encoded SOAP over MSMQ. This binding can only be used for WCF-to-WCF communication.

What are Volatile queues?

Answers:- There are scenarios in the project when you want the message to deliver in proper time. The timely delivery of message is more important than losing message. In these scenarios, Volatile queues are used.
Below is the code snippet, which shows how to configure Volatile queues. You can see the binding Configuration property set to Volatile Binding. This code will assure that message will deliver on time but there is a possibility that you can lose data.


<!-- use appSetting to configure MSMQ queue name -->
<add key="queueName" value=".\private$\ServiceModelSamplesVolatile" />

<service name="Samples.StockTickerServ"
<!-- Define NetMsmqEndpoint -->
<endpoint address="net.msmq://localhost/private/ServiceModelSamplesVolatile"
contract="Samples.InterfaceStockTicker" />

<binding name="volatileBinding"

What are Dead letter queues?

The main use of queue is that you do not need the client and the server running at one time. Therefore, it is possible that a message will lie in queue for long time until the server or client picks it up. But there are scenarios where a message is of no use after a certain time. Therefore, these kinds of messages if not delivered within that time span it should not be sent to the user.
Below is the config snippet, which defines for how much time the message should be in queue.


<binding name="MyBindings"

What the different transaction options ?

In the previous code we have use ‘TransactionFlowOption’. We can specify transaction in 3 ways in WCF:-


This is a default option. Using this option no transaction will be propagated across the binding. If any client attempts to call the WCF service in a transaction it will be ignored for this option.


This option specifies that client can call this WCF service in a transaction. It’s not compulsory that the service needs to be called in a transaction. You can call without the transaction also.


This option specifies that client must call the WCF service in a transaction mode. If the WCF service is called without transaction, ‘FaultException’ will be raised.


what are the advantages of hosting WCF Services in IIS as compared to self-hosting?

There are two main advantages of using IIS over 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 loose 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.
In case of self-hosting both the above features, you will need to code yourself. Lot of work right!!. That is why IIS is the best option for hosting services until you are really doing something custom.
Below figure shows where the recycle option is located in IIS. You need to click on the DefaultAppool and then Properties.

Figure 16:- IIS recycle option

What is one-way operation?

IsOneWay equal to true ensures that the client does not have to wait for the response. So methods marked by IsOneWay to true should always return void. In this, the caller does not get anything in return so it is called as one-way communication.
In order to understand one-way implementation in WCF lets make a code walkthrough of a sample.
Note: - You can find code for the same in “WCFIsOneWay” folder in CD.

Figure 17: - One-Way in action

Above is the code snippet, which describes practically how one way works in WCF. The above given code snippet is numbered. Below is the explanation according to the numbers marked in figure:-
1 - This is the code snippet of the server service. We have created a method called as doHugeTask. DoHugeTask makes the method sleep for 5000 MS and then displays the time when the task is completed.
2 - This code snippet is for client. It creates a proxy object of serviceIsOneWay and calls the doHugeTask method. After calling the doHugeTask, the client execution continues ahead. So as a proof, we display the time when the method calling was completed.
3 - This screen shot shows the output given by both server and client. The top window displays the server output and the below windows displays the client output.

Note: - You can find the code for the same in WCFIsOneWay folder. For generating the proxies you have to follow the same steps which are shown in the previous steps.

So run the server program first i.e. ServiceIsOneWay and run the client later. You will see the client runs the doHugeTask and moves ahead. Therefore, the client completion time is less than the server is. One more thing to understand is that one way does not give any notification back of completion. Therefore, it is like fire and forgets.

Can you explain duplex contracts in WCF?

In duplex contracts when client initiates an operation the server service provides a reference call back Uri back to the client. So the client initiates a call using the proxy class and when server finishes its work it notifies the client using the callback channel. This is called as duplex messaging in WCF. If you remember in the previous question, we had no way to know when the server finished its task.

 Figure 18:- Duplex Service code

Let us try to understand the duplex concept by doing a small sample. The code snippet is as shown in the above figure. We will extend the previous sample, which was shown in the first question only that now we will provide the notification to the client once the doHugeTask is completed.
The first step is to change the service class. Above is the code snippet of the service class. Again, we have numbered them so that we can understand how to implement it practically line by line. So below is the explanation number by number:-
1 - In the service contract attribute we need to specify the callback contract attribute. This Callback Contract attribute will have the interface, which will define the callback.
2 - This is the interface which client will call. In order that it should be asynchronous, we have defined the one-way attribute on the doHugeTask method.
3 -This is the most important interface. As it forms the bridge of communication between server and client. The server will call the client using Completed method. Client needs to provide implementation for the completed method at the client side and server will call that method once it completes the doHugeTask method.
4 and 5 - In this we implement the Interface Duplex interface and provide implementation for doHugeTask () method.
6 - This is an important step. The OperationContext.Current.GetCallBackChannel will be used to make callback to the client.
7 - We will expose the service using HTTP protocol. In this sample, because we want to do duplex communication we need to use wsDualHttpBinding rather than just using simple Http Binding. This new binding configuration is then assigned to the end on which the service is hosted.
This completes the server side explanation for duplex.

Figure: - 19 Duplex Client side code

Above is the code snippet for client side. So let us explain the above code with numbers.
1- We implement the completed method. This is the callback method, which the server will call when doHugeTask is completed.
2- In this step we create object of the Instance Context class. Instance Context represents context information of a service. The main use of Instance Context is to handle incoming messages. In short, proxy is used to send messages to server and Instance Context is used to accept incoming messages.
3 -In this step we pass the Instance Context object to the constructor of the proxy. This is needed, as the server will use the same channel to communicate to the client.
4 - In this section two windows are shown. The top windows is the servers output and the below windows is of the client. You can see in the below window that server as made a callback to the client.

Note: - You can get source code for the same in WCFDuplex folder. Feel Free to experiment with it. Try making one simple project of client to client chat using WCF duplex fundamentals I am sure your doubts will be cleared in and out.

How can we host a service on two different protocols on a single server?

Let us first understand what this question actually means. Let us say we have made a service and we want to host this service using HTTP as well as TCP. You must be wondering why to ever host services on two different types of protocol. When we host a service, multiple types of client consume it and it’s very much possible that they have there own protocol of communication. A good service has the capability to downgrade or upgrade its protocol according the client who is consuming him.
Let us do a small sample in which we will host the ServiceGetCost on TCP and HTTP protocol.

Note: - You can the below sample in “WCFMultipleProtocolGetHost” folder in the CD provided.

Below is the code snippet pasted from the same sample? As usual, we have numbered them and here is the explanation of the same:-
1 and 2 - As we are hosting the service on two protocols we need to create two objects if the URI. You can also give the URI through config file. Pass these two objects of the URI in the constructor parameter when creating the service host object.


Figure 20:- Server side code for Multi Protocol hosting

3 – In the config file we need to define two bindings and end as we are hosting the service in multiple protocols.
Once we are done the server side coding its time to see make a client by which we can switch between the protocols and see the results. Below is the code snippet of the client side for multi-protocol hosting.

Figure 21:- Multi Protocol Client code

Let us understand the code:-
1 - In the generated config file we have added two ends. When we generate the config file, it generates only for one protocol. The other end has to be manually added.
2 - To test the same we have a list box, which has the name value given in the end point.
3 - In the list box select event we have then loaded the selected protocol. The selected protocol string needs to be given in the proxy class and finally call the proxy class GetTotalCost.

How can we use MSMQ bindings in WCF?

First let us understand why MSMQ came in to picture and then rest will follow. Let us take a scenario where your client needs to upload data to a central server. If everything will works fine and the server is available 24 hours to client then there are no issues. In case the server is not available, the clients will fail and the data will not be delivered. There is where MSMQ comes in to picture. It eliminates the need of persistent connection to a server. Therefore, what you do is deploy a MSMQ server and let the clients post message to this MSMQ server. When your actual server runs, it just picks up the message from the queue. In short, neither the client nor the server needs to be up and running on the same time. In WCF we have a client and service model and in real world it is very much practical possible that both the entities will not be available at one time.
In order to use MSMQ you need to install the Message queuing by click on Install windows component and selecting MSMQ queuing. Once that done we are all set to make our sample of MSMQ using WCF

 Figure 22:- MSMQ Installation

This sample will be simple. We send some messages from the client and keep the server down. As the server is down it will make postings to the MSMQ server. Then we will run the server service and service should pick up the message and display the same.

Figure 23:- MSMQ Server side code walkthrough

Above snippet is the server side code. So let us understand the whole snippet:-
1 – First thing is the queue name where the messages will go if the server is not running. The server name we can get from the config file. You can see in the above snippet we have defined the Mismanage in App.config file.
2 – We first check does this queue exist if it exists then go-ahead. If not then go to create a queue. Please note you need import using System. Messaging namespace. Then we can use the Message Queue to create a queue if the queue does not exist.
3 – First thing which should surprise you is why we are creating a URI with HTTP protocol as we are going to use MSMQ. Ok! This is bit tricky but fun. As we know in order to connect to this service, we need to generate a client proxy using SVCUTIL. Therefore, this URI will help us do that. It is not actually used by the client to connect.
4 – We need our end and the MSMQ bindings.
5 and 6 – Again as usual we need is an interface and implementation for the same. In implementation we have created a method called send Message.
Once the above steps are executed, run the server and generate the client proxy using SVCUTIL utility.
Now comes the final step making a client. One change you need to make is change the address to the MSMQ server in the app.config. In this, we have just looped ten times and fired an offline message. Please note to keep your server down.

Figure 24:- MSMQ Client side code

Now go to computer management and you can see your queue messages waiting to be picked by the server. Run the server and below should be the output. If you come back again you will see that there are no messages in the queue.

Figure 25:- MSMQ Server side display

One of the important concepts is to understand when to use MSMQ protocol. When we expect that client and server will not be available, at one time this is the best option to opt for.

What different transaction isolation levels provided in WCF?

Transactions assure that a group of related activity occurs as a single atomic unit. In simple words, every activity in the unit must either all succeed or all should fail. WCF provides a central transaction system that can be used to handle transaction operations. One of the things WCF provides is a single unified transaction system for both database and non-database activity. For instance, BeginTrans and CommitTrans are database related syntaxes but we can not use the same for other activities like if we want to upload all message in a single transaction to a MSMQ server. One thing to note is that WCF transaction abides to WS specifications. That means any other language like JAVA can take advantage of this transaction…. I think that is the best part of WCF embracing other languages.

Figure 26:- Transactions in WCF

In order to support transaction the service should first support transactions. Above is a simple code snippet of the server service and client and explanation for the same:-

The top code snippet is of the server service and the below code snippet is of the client.

1 - At interface level the operation contract is attributed with [Transaction Flow] attribute. There are three values for it Allowed (which mean operation mar or may not be used in transaction), Not Allowed (Where it is never used in transaction) and required (Where the service can only be used in transactions). Below code snippet currently says that this service can only be used with transactions.

2 - In this section the [Service Behavior] attribute specifies the transaction isolation level property. Transaction isolation specifies the degree of isolation most compatible with other applications. So let us review what are the different levels you can provide in transaction isolation.
The data affected by a transaction is called volatile.
Chaos: - pending changes from more highly isolated transactions cannot be overridden.
Read Committed: - Volatile data can be modified but it cannot be read during the transaction.
Read Uncommitted: - Volatile data can be read as well as modified during the transaction.
Repeatable Read: - Volatile data can be read but not modified during the transaction and new data can be added.
Serializable: - Volatile data can be only read. However, no modifications and adding of new data is allowed.
Snapshot: - Volatile data can be read. However, before modifying the data it verifies if any other transaction had changed data. If yes then it raises error.
By default, the System. Transactions infrastructure creates Serializable transactions.

3 - This defines the transaction behavior with in the service. [Operation Behavior] has a property called as transaction scope. Transaction Scope setting indicates that operation must be called within a transaction scope. You can also see TransactionAutoComplete is set to true which indicates that transaction will complete by default if there are no errors. If you do not provide the TransactionAutoComplete to true then you will need to call OperationContext.Current.SetTransactionComplete() to make the transaction complete.
Now let us make a walkthrough of the client side code for the service.

4 and 5 - You can see from the client we need to define Isolation level and the scope while making the call to our Update Accounts method

Can we do transactions using MSMQ?

While doing MSMQ there can be scenarios in the project, where we would like all the messages are uploaded to either MSMQ or all messages read from MSMQ. After any message is read from MSMQ, it is deleted from the queue. Therefore, some times this can be critical if there are exceptions in reading or uploading messages. As said before WCF transaction can be applied to database as well as other operations like MSMQ. So let us try to understand the same by doing a small sample.
Below is a numbered code snippet of MSMQ transactions.

1 - Send message is the exposed method in the service. We have marked this method as TransactionScopeRequired=true

2 - On the client side we have use the transaction scope to say that we are starting a transaction to MSMQ server. You can see we have used the send Message to send the messages to MSMQ.

3- We can then use Complete or Dispose method to complete or rollback the transactions.
The below MSMQ transaction code ensures that either all messages are send to the server or none are sent. Thus satisfying consistency property of transactions.

Figure 27:- Transaction snippet code

More WCF Interview Questions & Answers here

Found this useful, bookmark this page to the blog or social networking websites. Page copy protected against web site content infringement by Copyscape

 Exclusive Interview Questions and Answers Categories