Service Behavior in WCF



The following is what is in this article:
  • Introduction
  • Transactions
  • Throttling
  • Attachment
  • Summary
Introduction

Your good behavior makes you a better person, am I right? Yes if you are showing your good behavior towards other people then better communication will form. Such as if you apply the right behavior on various parts of your WCF system, you will be able to influence the WCF service in regard to things concurrency, session management, throttling and transactions. Behaviors can be applied at the service, operation, endpoint and contract levels.

Few behavior configurations can be done on the configuration side and a few can be at the source code side.

Service Behavior

The [Service Behavior] attribute is used to apply behavior at the service level. It allows you to control things such as: 
  • Concurrency
  • Throttling
  • Transaction
  • Session Management
  • Thread Behavior
The preceding can be done by setting its properties.

Service Behavior Properties

S.No. Property What for?
1 Address Filter Mode Allows you to change the Message Filter. This property has the three values
Any, Exact and Prefix. Used by the Dispatcher to identify the correct endpoint responsible to handle incoming messages.
2 Automatic Session ShutDown Boolean Field, stops the server from closing the session when all the incoming messages have been processed. By Default it is true. By make it false you are able to control the session lifetime.
3 Concurrency Mode This is set if the service runs on a single thread or multiple threads.
4 IgnoreExtensionDataObject Boolean Field. False by default. If set to true then any unknown serialization data is not sent with the message.
5 IncludeExceptionDetailinFaults Set to True if you want to get the unhandled exception sent to the client as a SOAP fault.
Set to False in a production environment, set to True in a development environment
6 InstanceContextMode Used to set the lifetime of the service instance. The allowed values are Per session, Per call and Single.
7 MaxItemsinObjectGraph This sets to Maximum allowed items in the serialized/deserialized object graph. Sometimes you receive an exception when you serialize/deserialize the maximum number of items. Increase this property to match your case.
8 ReleaseServiceInstanceOnTransactionComplete If set to true, the service object will be released when the active transaction is complete.
9 TransactionAutoCompleteOnSessionClose Set to true if you want to mark the active transaction as complete when the session is closed by client without error.
10 TransactionTimeOut Sometimes a transaction can take more time to complete. You can set a timeout after which the session is considered as aborted and the rollback process is started.

Session management and the Concurrency are really important and are the most useful properties in Service Behavior. In my future article you can find detailed explanations on Session Management and concurrency, but here we will concentrate only on the Transactions and Throttling.

Transactions

A transaction is a logical unit of work consisting of multiple activities that must either succeed or fail together. For example, you are trying to make an online purchase for a dress; your amount is debited from the bank, but your ordered dress was not delivered to you. So what did you get from the preceding example? Bank operations hosted in a separate service and the online purchase service (Ordering the goods) hosted as another separate service. For the preceding example the online purchase service did not work well as expected due to the database query error, without knowing it the Bank operations were completed perfectly. For this we really need transactions to ensure that either of the operations should succeed or fail. Before we go to the WCF transactions, let us discuss what exactly are the basics behind the transactions.

The following are the types of the Transactions:

  • Atomic
  • Long Running
Atomic transactions are the ones that take less time to finish, for example updating the relative tables in the database. As I said in the last paragraph, the bank related operation table got updated, but the Purchase related tables were not updated. This we can call as an Atomic Transaction.

Long Running transactions are the ones that take more time to finish. For example, a client sending a request to the service but it takes more days or months to provide a response to the client. Yes of course until that period of time has completed we should not lock down the resources like SQL Server, so this case cannot be handled by Atomic Transactions.

Transaction Protocols 
  • Lightweight Protocol
  • OleTx Protocol
  • WSAT Protocol
Lightweight Protocol: It is used when a single application inside an appdomain is working with a single RM (SQL Server or any component participating in transactions).

OleTx Protocol: It allows Cross AppDomain, used for Windows-intranet scenarios. No cross-platform communication allowed, no communication through the firewall is allowed.

WSAT Protocol: Similar to OleTx, but this will go across firewalls and platforms.

I hope the preceding one is still unclear for you guys, let me try to explain it in another way. A WCF service calls into SQL Server for multiple updates to be done, that are all enlisted as a single transaction. A WCF service is called by the clients running on the same machine or various Windows machine. In this case OleTx protocol is used to maintain the transaction. In the same above situation if one of your clients is a Java client, the WSAT protocol will be used since it is a cross-platform interoperability.



WCF Transactions

Now to see here how the transactions will be done using WCF. The following is the really important procedure to configure transactions.
  • Transaction Bindings
  • Transaction Flow Option
  • TransactionScope (Client and Server)
  • Configuring Transaction Modes
Transaction Bindings

Before you think about achieving the transaction in WCF, we need to consider the binding to choose, not all bindings normally support transactions. The following are the bindings that support transactions:
  • NetNamedPipeBinding
  • NetTCPBinding
  • WSHttpBinding
  • WSDualHttpBinding
  • WSFederationHttpBinding
NetNamedPipeBinding and NetTCPBinding support transactions because they deal with AppDomains very well, either in the same machine or another machine.
 
WS bindings are not an issue, they implement the Web Services Enhancement standards (WSE) namely WS-Atomic Transaction. The following is the declaration of the binding:
  1. <bindings>  
  2. <wsHttpBinding>  
  3. <binding name="wshttpbind" transactionFlow="true"></binding>  
  4. </wsHttpBinding>  
  5. </bindings>  
Transaction Flow Option

We should declare this option in the service interface methods. The following are the three sets of options available:
  • Transaction Flow option: Not Allowed
  • Transaction Flow option: Allowed
  • Transaction Flow option: Mandatory
Transaction Flow Option: Not Allowed

The client cannot propagate its transaction into the service operation, even if the binding supports transactions. Even if the client propagates its transaction, it will be simply ignored, no exception will be thrown.


Transaction Flow Option: Allowed

The service operation allows the transaction propagation if the client wants to. That is, the client creates the transaction, the binding that you are using also supports transactions. If the transaction flow option is allowed in the service method then the transaction will be propagated to the service. In other words the transaction will not be Propagated. What if, when the client propagates the transaction, the binding in the service does not support transactions? As a result an exception will be thrown when the client propagates the transaction.



Transaction Flow Option: Mandatory

The client and the service must use the binding that supports transactions, any violations will result in an exception.

 
Transaction Scope

We will now discuss two important attributes we need to define in the transaction, they are TransactionScopeRequired and the TransactionAutoComplete properties in operation behavior.

TransactionScopeRequired: True, it means if the client propagates the transaction to the operation, it will be the one to use in the service side. If the client did not propagate any transaction then it creates its own transaction and uses it. Please look at the following source code to understand how we should declare it in the client and server side.
 


TransactionAutoComplete: True, this setting instructs the WCF to auto-commit the transaction at the end of the code block. It can be configured only at the service level.

Configuring Transaction Modes

So far we have learned about the usage of transaction attributes, now let's see various options in configuring transaction modes.

Use Client's T or Use your OWN T

Did you understood the Title "Use Client's T or Use your OWN T"? I hope you couldn't .

Yes, let me explain it here. The following procedure will determine whether the client's transaction is propagated or otherwise create your own transaction and use it.
  • Set the transaction Flow attribute to True on both the client and service
  • Set the Transaction Flow allowed on the operation contract
  • Set the TransactionScopeRequired and TransactionAutoComplete attributes of the operation contract to True


If you are still not clear then please refer to the attached source code.

Use only Client's T

Use only Client's T: Yes the following procedure determines whether the Hello Service, doesn't use or create a transaction, use only the client's transaction.
  • Set the transaction Flow attribute to True on both the client and service
  • Set the Transaction Flow Mandatory on the operation contract
  • Set the TransactionScopeRequired and TransactionAutoComplete attributes of operation contract to True
Use only Service's T

Use only Service's T: The following procedure determines whether that Hello Service, doesn't use another transaction, use your own transaction (Service)
  • Set the transaction Flow attribute to True on both the client and service
  • Set the Transaction Flow Not Allowed on the operation contract
  • Set the TransactionScopeRequired and TransactionAutoComplete attributes of operation contract to True
Don't use T

Don't use T: The following procedure determines whether that Hello Service, doesn't use any transaction.
  • Set the transaction Flow attribute to True on both the client and service
  • Set the Transaction Flow Not Allowed on the operation contract
  • Set the TransactionScopeRequired and TransactionAutoComplete attributes of operation contract to True
So far we have seen what transactions are. What are all the types of protocols it uses? What are all the procedures involved in configuring transactions in WCF? How should we configure different transaction modes? Now we shall see what exactly the process involved during the transaction. The transactional manager manages the transactions across the process or boundaries. It uses either the OleTx Protocol or the WSAT protocol to manage, namely the Distributed Transaction Manager (DTC). DTC actually uses the management protocol 2 Phase Commit Protocol to manage the distributed transaction across machines. There are two phases that DTM uses to manage the distributed transaction.
  • Prepare
  • Commit
In the Prepare phase, DTC asks each resource manager (SQL) to vote on either commit or abort through an RPC call, then each Resource manager (SQL) gives their votes to DTC saying Yes or No.

In the Commit phase, DTC asks all resource managers to commit or abort based on the votes received yes or no.

Coordinator Cohort
QUERY TO COMMIT
-------------------------------->
VOTE YES/NO prepare*/abort*
<-------------------------------
commit*/abort* COMMIT/ROLLBACK
-------------------------------->
ACKNOWLEDGMENT commit*/abort*
<--------------------------------
end

But please don't worry about which transaction manager I need to use, how I need to manage and all, because all these operations are managed by the WCF internally. Please refer to the attached code for further details.

Throttling

Service Behavior: Throttling exposes properties that you can control how many instances or sessions are created at the application level. For example the number of service instances, the creating should not be more than the specific value.

MaxConcurrentCalls

To define the number of concurrent calls that the service will accept. The default value in .Net 4.0 is 16 * processor count. Prior to .Net 4.0 it was 16.

MaxConcurrentSessions

To define the number of session channels that the service will accept. By default in .Net 4.0 the default value is 100 * processor count, prior to .Net 4.0 the default value was 10.

MaxConcurrentInstances

To define the number of service instances will be created. By default in .Net 4.0 the default value will be 26, whereas in .Net 4.0 the default value will be 116 * processor count.


Attachment

Please refer to the folder Transaction for the Transaction sample, refer to the folder Throttling for the Throttling samples
 
Summary

CTS: Concurrency, Throttling, Transactions are the important topics in service behavior. 

Up Next
    Ebook Download
    View all
    Learn
    View all