Tuesday, September 13, 2011

Interview Questions - WCF

What are the important principles of SOA (Service oriented Architecture)?
Enabled by Web services
Technology neutral
Endpoint platform independence.

Standardized
Standards-based protocols.

Consumable
Enabling automated discovery and usage.
Enabled by SOA
Reusable
Use of Service, not reuse by copying of code/implementation.

Abstracted
Service is abstracted from the implementation.

Published
Precise, published specification functionality of service interface, not implementation.

Formal
Formal contract between endpoints places obligations on provider and consumer.

Relevant
Functionality presented at a granularity recognized by the user as a meaningful service.
What are the main components of WCF?
The main components of WCF are
1.       Service class.
2.       Hosting environment.
3.       End point.
What is a service contract, operation contract, Data Contract and Message Contract?
Service Contract:
Service Contract specifies the description of methods which our service will provide to consuming application. For WCF to identify contracts for the service, we need to use interface/class with [ServiceContract] attribute. In WCF we can do interface/Class level programming.
Operation Contract:
We need to expose some methods to consuming application to use our services. Those methods will have [OperationContract] attribute. Making them public will not make them accessible from outside. So OperationContract Specifies the methods can be accessible from outside.
Data Contracts:

WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service.

Message Contracts:

Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body. Whereas data contracts enable interoperability through the XML Schema Definition (XSD) standard, message contracts enable you to interoperate with any system that communicates through SOAP. Using message contracts gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. This allows use of simple or complex types to define the exact content of the SOAP parts.

What are the various ways of hosting a WCF service?
1.       Self-hosting.
2.       IIS hosting.
3.       Windows hosting.
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 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.
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.


What is the difference WCF and Web services?
Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.

Second web services are not flexible. However, WCF 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.

We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc.

What are different bindings supported by WCF?
WCF includes predefined bindings. They cover most of bindings widely needed in day-to-day application. However, just in case 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:-This 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 inter process 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 is one-way operation?
There are cases when an operation has no returned values and the client does not care about the success or failure of the invocation. To support this sort of fire-and-forget invocation, Windows Communication Foundation offers one-way operations. After the client issues the call, Windows Communication Foundation generates a request message, but no correlated reply message will ever return to the client. As a result, one-way operations can't return values, and any exception thrown on the service side will not make its way to the client. One-way calls do not equate to asynchronous calls. When one-way calls reach the service, they may not be dispatched all at once and may be queued up on the service side to be dispatched one at a time, all according to the service configured concurrency mode behavior and session mode. How many messages (whether one-way or request-reply) the service is willing to queue up is a product of the configured channel and the reliability mode. If the number of queued messages has exceeded the queue's capacity, then the client will block, even when issuing a one-way call. However, once the call is queued, the client is unblocked and can continue executing while the service processes the operation in the background. This usually gives the appearance of asynchronous calls. All the Windows Communication Foundation bindings support one-way operations.
The OperationContract attribute offers the Boolean IsOneWay property, which defaults to false, meaning a request-reply operation. But setting IsOneWay to true configures the method as a one-way operation:
[ServiceContract]
interface IMyContract
{
   [OperationContract(IsOneWay = true)]
   void MyMethod()
}
Because there is no reply associated with a one-way operation, there's no point in having any returned values or results, and the operation must have a void return type without any outgoing parameters. Since Windows Communication Foundation does not have any hooks into the language compiler and can't verify proper usage at compile-time, it enforces this by verifying the method signature when loading up the host at run time and throwing an InvalidOperationException in case of a mismatch.
The fact that the client doesn't care about the result of the invocation does not mean the client doesn't care if the invocation took place at all. In general, you should turn on reliability for your services, even for one-way calls. This will ensure delivery of the requests to the service. However, with one-way calls, the client may or may not care about the invocation order of the one-way operations. This is one of the main reasons why Windows Communication Foundation allows you to separate enabling reliable delivery from enabling ordered delivery and execution.
Can you explain duplex contracts in WCF?
A duplex service contract is a message exchange pattern in which both endpoints can send messages to the other independently. A duplex service, therefore, can send messages back to the client endpoint, providing event-like behavior. Duplex communication occurs when a client connects to a service and provides the service with a channel on which the service can send messages back to the client.
Duplex contract allows a service to callback to a client. When a contract is defined for a service, It is possible to specify a corresponding callback contract. The standard service contract defines the operations of the service that can be invoked by the client. The callback contract defines the operations of the client that can be invoked by the service. It is the client's responsibility to implement the callback contract and host the callback object. Each time the client invokes a service operation that is associated to the callback contract, the client supplies the necessary information for the service to locate and invoke the callback operation on the client.       
What are Volatile queues?
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
.
 

behaviorConfiguration="CalculatorServiceBehavior">
...
binding="netMsmqBinding"
bindingConfiguration="volatileBinding"
contract="Samples.InterfaceStockTicker" />
...

durable="false"
exactlyOnce="false"/>
...

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.
 
deadLetterQueue="Custom"
customDeadLetterQueue="net.msmq://localhost/private/ServiceModelSamples"
timeToLive="00:00:02"/>
Can you explain transactions in WCF?
A transaction is a collection or group of one or more units of operation executed as a whole. Another way to say it is that transactions provide a way to logically group single pieces of work and execute them as a single unit, or transaction.
For example, when you place an order online, a transaction occurs. Suppose you order a nice 21-inch wide-screen flat-panel monitor from your favorite online hardware source. Assume you were to pay for this monitor with a credit card. You enter the information required on the screen and click the "Place Order" button. At this point, two operations occur. The first operation takes place when your bank account is debited the amount of the monitor. The second operation occurs when the vendor is credited that amount. Each of those operations is a single unit of work.
Now imagine that one of those operations fails. For example, suppose that the money was removed from your bank account for the purchase of the monitor, but the payment to the vendor failed. First, you wouldn't receive your anxiously awaited monitor, and second, you would lose the amount of money for the cost of the monitor. I don't know about you, but I would be quite unhappy if this happened.
Conversely, a payment could be made to the vendor without debiting your account. In this case, the debit from your account failed but the payment to the vendor succeeded. You would likely receive the purchase item without having paid for it. Although this scenario is preferable to the former one, neither is acceptable in that in either case, someone is not receiving what is rightfully theirs.
The solution to this is to wrap both of these individual operations into a single unit of execution called a transaction. A transaction will make sure that both operations succeed or fail together. If either of the operations fails, the entire unit of work is cancelled and any and all changes are undone. At this point, each account is in the same state it was before you attempted your purchase. This undoing is known as "rolling back" the transaction.
This ensures that you receive your monitor and the vendor receives its money. Both parties are now happy and your confidence in doing business online hasn't wavered.
A pure and successful transaction has four characteristics. You can use the mnemonic aid "ACID" to help you remember each of them:
  • Atomic
  • Consistent
  • Isolated
  • Durable
Atomic
The word "atomic" comes from the Greek word "atamos," meaning "indivisible; cannot be split up." In computing terms, this meaning also applies to transactions. Transactions must be atomic, meaning either all the operations of the transactions succeed or none of them succeed (that is, all successful operations up to the point of failure are rolled back).
In the case of the monitor order, the money is removed from the bank account and deposited into the vendor bank account. If either of those operations fails, each account returns to the state it was in prior to the start of the purchase attempt.
Consistent
Consistent transactions mean that the outcome is exactly what you expected it to be. If you purchase the monitor for $300 and you have $1,000 in the bank account, consistent transactions mean that you expect to be charged $300 and have $700 remaining in the bank account when the transaction is committed and complete.
Isolated
Isolated transactions are "private," meaning that no one else knows about the transaction until it is committed.
For example, suppose you have $1,000 in a bank account from which to purchase the monitor. You purchase the monitor for $300, and during the purchase of the monitor, while the transaction is taking place, your husband or wife is at the local ATM checking the balance of the account from which the money for the monitor is being withdrawn.
Isolated transactions are invisible to all other transactions, and in this example the husband or wife would see a balance of $1,000. In fact, if the husband or wife were to withdraw money from the ATM while the online purchase was taking place, both transactions would be isolated transactions, completely unknown to one another.
Durable
Durable transactions must survive failures. When a transaction is complete, it is "committed," meaning that the changes have taken effect. For a transaction to be durable, it must maintain its committed state if there is a failure.
What is a failure? It could be a power outage, hardware failure, and so on. Regardless of the failure, the transaction must survive it.
Suppose that after the processing of the transaction, someone yanks the power cord out of the server that is processing your order. A durable transaction survives this failure. When the power is restored to the server, the result of the transaction must be in the committed state.
Transaction Attributes in System.ServiceModel
When version 2.0 of the .NET Framework was released, it included a new namespace (System.Transactions) that makes transaction programming easy and efficient. The System.Transactions namespace supports transactions initiated by many platforms including SQL Server, MSMQ, ADO.NET, as well as MSDTC (Microsoft Distributed Transaction Coordinator).
Windows Communication Foundation utilizes the many available objects of this namespace to provide all the necessary transaction capabilities you will need when building your WCF services and client applications.
ServiceBehavior Attribute
The [ServiceBehavior] attribute has three properties that deal with handling and managing transactions. Each is shown in the following list:
·         TransactionAutoCompleteOnSessionClose: Specifies whether pending transactions are completed when the current session closes.
·         TransactionIsolationLevel: Determines the isolation level of the transaction.
·         TransactionTimeout: Specifies the period in which a transaction has to complete.
The first of these is the TransactionAutoCompleteOnSessionClose property. It should be used for cases where you want to ensure that transactions are completed when the session is closed. As such, the transaction will either be committed or rolled back when the session is closed, depending on its state.
The one that needs to be highlighted here is the TransactionIsolationLevel property. This property determines how the data is handled when other transactions make modifications to the data. It also has an impact on how long your transaction can hold locks on the data, protecting it from other transactions.
The TransactionTimeout property determines how long the transaction can run before it is cancelled. If the transaction has not completed before the timeout value has been reached, the transaction is rolled back. Great care must be taken when choosing a timeout interval. Too high of an interval will cause needless wait times when a failure has occurred. Too small of an interval will cause the transaction to fail before it has had time to complete.
These properties are properties of the [ServiceBehavior] attribute, which is applied to the class that implements the service interface. The following code snippet shows the three transaction properties applied to the [ServiceBehavior] attribute:
[ServiceBehavior(TransactionAutoCompleteOnSessionClose=true,
      TransactionIsolationLevel=IsolationLevel.ReadCommitted,
      TransactionTimeout="00:00:30")]
public class ServiceClass : IServiceClass
{
   [OperationBehavior]
   string IServiceClass.GetText()
   {
      StreamReader sw = new StreamReader(@"c:\Test\WCFServiceTest.txt");
      return sw.ReadLine();
   }
}
In this case, the TransactionAutoCompleteOnSessionClose property is set to true, the TransactionIsolationLevel is set to ReadCommitted, and the TransactionTimeout is set to 30 seconds. The TransactionTimeout property value is of a Timespan object.
Prior to running the example, make sure that the c:\Test\WCFServiceTest.txt file exists and contains at least a few words of text. If your test file is located somewhere else, make sure the example is pointed to the correct location.
OperationBehavior Attribute
The [OperationBehavior] also has a couple of properties related to transactions. The two properties are:
  • TransactionAutoComplete: Specifies that transactions will be auto-completed if no exceptions occur.
  • TransactionScopeRequired: Specifies whether the associate method requires a transaction.
The characteristics of a successful transaction were discussed earlier in this article. Both the TransactionAutoComplete property and TransactionScopeRequired property help fulfill the durable requirement because it will automatically complete a transaction, thus ensuring that the specific operation is successful.
The following example illustrates a service operation that is annotated with the [OperationBehavior] attribute, which specifies the two transaction properties:
[OperationBehavior(TransactionAutoComplete=true,
TransactionScopeRequired=true)]
string IServiceClass.GetText()
{
    StreamReader sw = new StreamReader(@"c:\wrox\WCFServiceTest.txt");
    return sw.ReadLine();
}
In this example, the TransactionAutoComplete property is set to true and the TransactionScopeRequired property is set to true as well.
TransactionFlow Attribute
The [TransactionFlow] attribute is used to specify the level at which a service operation can accept a transaction header. This attribute has a single property and is the attribute used to annotate a service operation method. The values for this property come from the TransactionFlowOption enumeration and are shown in the following list:
  • Allowed: Transaction may be flowed.
  • Mandatory: Transaction must be flowed.
  • NotAllowed: Transaction cannot be flowed.
This property and the associated values are used to indicate whether transaction flow is enabled for the associated method.
The following example illustrates a service operation that is annotated with the [TransactionFlow] attribute, which specifies the level at which the operation is willing to accept incoming transactions. This example sets the level at mandatory, signifying that transactions are required for this operation:
[TransactionFlow(TransactionFlowOption.Mandatory)]
int IServiceClass.MultiplyNumbers(int firstvalue, int secondvalue)
{
    return firstvalue * secondvalue;
}
The default value for this property is NotAllowed.
A flowed transaction is a situation in which a transaction id is passed over the wire and used on the receiving side to perform work, usually enlisting in the corresponding transaction and executing within that scope.
WS-Atomic Transaction
Windows Communication Foundation utilizes the WS-AT (WS-Atomic Transaction) protocol to flow transactions to other applications. The WS-AT protocol is an interoperable protocol that enables distributed transactions to be flowed using web service messages, and incorporates a two-phase commit protocol to facilitate the outcome between distributed applications and transaction managers. The transaction protocol used when flowing a transaction between a client and service is determined by the binding that is exposed on the endpoint.
You do not need to use this protocol if your communication is using strictly Microsoft technology (WCF). Simply enabling the TransactionFlow attribute will get you the desired results. However, this protocol will be necessary if you are flowing transactions to other platforms and third-party technologies.
Specifying Transactions Through Configuration
On the client side, transaction flow is enabled via the binding. The following example, several properties on the [ServiceBehavior] and [OperationBehavior] attributes were set so that they enabled transactions on the service. When the service references were added to the client, the client interrogated the consumed service and set the appropriate binding attributes in the configuration file.
Transaction flow is enabled by setting the value of the transactionFlow attribute to true, as shown by the highlighted line in the following code:
       
                 closeTimeout="00:01:00"
                 openTimeout="00:01:00"
                 receiveTimeout="00:10:00"
                 sendTimeout="00:01:00"
                 bypassProxyOnLocal="false"
                 transactionFlow="true"
                 hostNameComparisonMode="StrongWildcard"
                 maxBufferPoolSize="524288"
                 maxReceivedMessageSize="65536"
                 messageEncoding="Text"
                 textEncoding="utf-8"
                 useDefaultWebProxy="true"
                 allowCookies="false">
         
                        maxStringContentLength="8192"
                        maxArrayLength="16384"
                        maxBytesPerRead="4096"
                        maxNameTableCharCount="16384" />
         
                           inactivityTimeout="00:10:00"
                           enabled="false" />
          
            
                        proxyCredentialType="None"
                        realm="" />
            
                      egotiateServiceCredential="true"
                      algorithmSuite="Default"
                      establishSecurityContext="true" />           
     
                binding="wsHttpBinding"
                bindingConfiguration="WSHttpBinding_IServiceClass"
                contract="WCFClientApp.TCP.IServiceClass"
                name="NetTcpBinding_IServiceClass">                         
 
Can we have two-way communications in MSMQ?
Yes