Blue Theme Orange Theme Green Theme Red Theme
 
Ads by Lake Quincy Media
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ADO.NET & Database » Managing Distributed Transactions with ADO.NET 2.0 using TransactionScope

Managing Distributed Transactions with ADO.NET 2.0 using TransactionScope

This article describes how to manage distributed transactions that can span multiple data sources in a Microsoft .NET application.

Author Rank:
Total page views :  64921
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

Introduction:

A transaction is a unit of work. You use transactions to ensure the consistency and integrity of a database. If a transaction is successful, all of the data modifications performed during the transaction are committed and made permanent. If an error occurs during a transaction, you can roll back the transaction to undo the data modifications that occurred during the transaction.

This article describes how to manage distributed transactions that can span multiple data sources in a Microsoft .NET application.

Distributed Transactions:

A distributed transaction spans multiple data sources. Distributed transactions enable you to incorporate several distinct operations, which occur on different systems, into an atomic action that either succeeds or fails completely.

Properties of a transaction:

  • Atomicity:
    A transaction is an atomic unit of work, an indivisible set of operations. The operations that you perform within a transaction usually share a common purpose, and are interdependent. Either all of the operations in a transaction should complete, or none of them should. Atomicity helps to avoid data inconsistencies by eliminating the chance of processing a subset of operations.
  • Consistency:
    A transaction preserves the consistency of data. A transaction transforms one consistent state of data into another consistent state of data. Some of the responsibility for maintaining consistency falls to the application developer, who must ensure that the application enforces all known integrity constraints.
  • Isolation:
    A transaction is a unit of isolation. Isolation requires that each transaction appear to be the only transaction manipulating the data store, even though other transactions might be running concurrently. Transactions attain the highest level of isolation when they have the ability to be serialized; at this level of isolation, the results obtained from a set of concurrent transactions are identical to the results obtained by running each transaction serially. A high degree of isolation can limit the number of concurrent transactions, and consequently, applications often reduce the isolation level in exchange for better throughput.
  • Durability:
    A transaction is the unit of recovery for a set of operations. If a transaction succeeds, the system guarantees that its updates will persist, even if the computer crashes immediately after the application performs a commit operation. Specialized logging allows the system restart procedure to complete unfinished operations so that the transaction is durable.

Creating Distributed Transactions:

The .NET Framework 2.0 includes the System.Transactions namespace, which provides extensive support for distributed transactions across a range of transaction managers, including data sources and message queues. The System.Transactions namespace defines the TransactionScope class, which enables you to create and manage distributed transactions.

To create and use distributed transactions, create a TransactionScope object, and specify whether you want to create a new transaction context or enlist in an existing transaction context. You can also exclude operations from a transaction context if appropriate.

You can open multiple database connections within the same transaction scope. The transaction scope decides whether to create a local transaction or a distributed transaction. The transaction scope, automatically promotes a local transaction to a distributed transaction if necessary, based on the following rules:

  • When you create a TransactionScope object, it initially creates a local, lightweight transaction. Lightweight transactions are more efficient than distributed transactions because they do not incur
    the overhead of the Microsoft Distributed Transaction Coordinator (DTC).
  • If the first connection that you open in a transaction scope is to a SQL Server 2005 database, the connection enlists in the local transaction. The resource manager for SQL Server 2005 works with
    the System.Transactions namespace and supports automatic promotion of local transactions to distributed transactions. Therefore, the transaction scope is able to defer creating a distributed
    transaction unless and until it becomes necessary later.
  • If the first connection that you open in a transaction scope is to anything other than a SQL Server 2005 database, the transaction scope promotes the local transaction to a distributed transaction
    immediately. This immediate promotion occurs because the resource managers for these other databases do not support automatic promotion of local transactions to distributed transactions.
  • When you open subsequent connections in the transaction scope, the transaction scope promotes the transaction to a distributed transaction, regardless of the type of the database.

Steps of creating distributed transaction:

  1. Instantiate a TransactionScope object.
  2. Open a connection with the database.
  3. Perform your database operations (insert, update & delete).
  4. If your operations completed successfully, mark your transaction as complete.
  5. Dispose The TransactionScope object.

If all the update operations succeed in a transaction scope, call the Complete method on the TransactionScope object to indicate that the transaction completed successfully. To terminate a transaction, call the Dispose method on the TransactionScope object. When you dispose a TransactionScope, the transaction is either committed or rolled back, depending on whether you called the Complete method:

  • If you called the Complete method on the TransactionScope object before its disposal, the transaction manager commits the transaction.
  • If you did not call the Complete method on the TransactionScope object before its disposal, the transaction manager rolls back the transaction.

TransactionScope How To:

A transaction scope defines a block of code that participates in a transaction. If the code block completes successfully, the transaction manager commits the transaction. Otherwise, the transaction manager rolls back the transaction. Bellow is a guide lines on how you can create and use a TransactionScope instance:

  1. Add a reference to the System.Transactions assembly.
  2. Import the System.Transactions namespace into your application.
  3. If you want to specify the nesting behavior for the transaction, declare a TransactionScopeOption variable, and assign it a suitable value.
  4. If you want to specify the isolation level or timeout for the transaction, create a TransactionOptions instance, and set its IsolationLevel and TimeOut properties.
  5. Create a new TransactionScope object in a using statement (a Using statement in Microsoft Visual Basic).
    Pass a TransactionScopeOption variable and a TransactionOptions object into the constructor, if appropriate.
  6. In the using block (Using block in Visual Basic), open connections to each database that you need to update, and perform update operations as required by your application. If all updates succeed, call the Complete method on the TransactionScope object
  7. Close the using block (Using block in Visual Basic) to dispose the TransactionScope object. If the transaction completed successfully, the transaction manager commits the transaction. Otherwise, the transaction manager rolls back the transaction.

Listing 1: TransactionScope C#:

using System.Transactions;

...

TransactionOptions options = new TransactionOptions();

options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;

options.Timeout = new TimeSpan(0, 2, 0);

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))

{

          using (SqlConnection connA = new SqlConnection(connStringA))

{

                    using (SqlCommand cmdA = new SqlCommand(sqlStmtA, connA))

                    {

                             int rowsAffectedA = cmdA.ExecuteNonQuery();

                             if (rowsAffectedA > 0)

                             {

                                       using (SqlConnection connB = new SqlConnection(connStringB))

                                       {

                                                using (SqlCommand cmdB = new SqlCommand(sqlStmtB, connB))

                                                {

                                                          int rowsAffectedB = cmdB.ExecuteNonQuery();

                                                          if (rowsAffectedB > 0)

                                                          {

                                                                    transactionScope.Complete();

                                                          }

                                                } // Dispose the second command object.

                                       } // Dispose (close) the second connection.

                             }

                    } // Dispose the first command object.

          } // Dispose (close) the first connection.

} // Dispose TransactionScope object, to commit or rollback transaction.

Listing 2: TransactionScope VB.NET:

Imports System.Transactions
...
Dim options As New TransactionOptions()
options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted
options.Timeout = New TimeSpan(0, 2, 0)
Using scope As New TransactionScope(TransactionScopeOption.Required, options)

Using connA As New SqlConnection(connStringA)

Using cmdA As New SqlCommand(sqlStmtA, connA)

Dim rowsAffectedA As Integer = cmdA.ExecuteNonQuery()        

If (rowsAffectedA > 0) Then

Using connB As New SqlConnection(connStringB)

Using cmdB As New SqlCommand(sqlStmtA, connB)

Dim rowsAffectedB As Integer = cmdB.ExecuteNonQuery()

If (rowsAffectedB > 0) Then

transactionScope.Complete()

End If

End Using ' Dispose the second command object.

End Using ' Dispose (close) the second connection.

End If

End Using ' Dispose the first command object.

End Using ' Dispose (close) the first connection.

End Using ' Dispose TransactionScope object, to commit or rollback transaction.

Conclusion:

A transaction scope defines a block of code that participates in a transaction. If the code block completes successfully, the transaction manager commits the transaction. Otherwise, the transaction manager rolls back the transaction.

Also you should know that you can TransactionScope with any Data Provider such as Oracle or OleDB or ODBC.


Login to add your contents and source code to this article
 About the author
 
Muhammad Mosa
Muhammad M. Mosa Soliman: Software Engineer, graduated from the Faculty of Computers & Information Systems year 2003-Ain Shams University- in Cairo. Working with Microsoft .NET technology since early beta releases. Main experiance based on ASP.NET, SharePoint Portal 2003 & SQL Server. Worked as trainer for Microsoft .NET for 2 years in Cairo. Likes to read about new technologies and self-learning. Extremly Hard worker when motivated. MCT MCSD.NET MCTS: .Net 2.0 Web/Windows Applications MCPD: Enterprise Application Developer MCTS: WSS 3.0 & MOSS 2007 Config
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Enhancement in Transaction of ADO.NET 2.0 by Chuck On May 6, 2006

Hi Mosessaur:

Your article was good. But can you please tell the enhancement features of Transaction in ADO.NET 2.0  wrt 1.0 or if you know any resources and link pertaining to that?

Thanks

CS

 

 

Reply | Email | Delete | Modify | 
Re: Enhancement in Transaction of ADO.NET 2.0 by Muhammad On May 6, 2006

The most important new feature in transaction operations in .NET is the System.Transaction Namespace with TransactionScope class that support Distriputed transactions.

This feature doesn't exist in .NET 1.x. and if you wished to do distriputed transaction in .NET 1.x you have to use serviced component, and this is really not so easy to build.

If I could find any white paper that would help you in this point I'll get back to you.

Regards

Reply | Email | Delete | Modify | 
Need Help by uzair On May 31, 2007

AOA Muhammad

I am basically a beginner and I got a very little knowledge of ASP.NET, I had done my BS Computer science and now doing my MSc. Software engineering. I have to start my Final project (desertation) from next month. I am interested in doing something using ASP.NET and other technologies. Can U please suggest me some good projects and any book which u suggest, which helps me in learning ASP.NET. I am waiting for your kind response.

Regards,

Uzair Zaman Sheikh

Reply | Email | Delete | Modify | 
Re: Need Help by Muhammad On June 3, 2007

Sorry for the delay Uzair.
you can visit this Online ebook Library for more about books. And for updates you can visit my blog. About projects I suggest to visit the learning section on ASP.NET web site and it contains really great resources including videos.

I wished I could help you more.

Regards,

Reply | Email | Delete | Modify | 
Re: Re: Need Help by uzair On January 28, 2008

AOA Muhammad,

I m sorry too for replying u late... thnx for your kind help.

 

A.H

Reply | Email | Delete | Modify | 
SQL Server 2005 Issue by Rahul On February 21, 2007
hi Muhammad, I have tried using your sample code in my application. Thing is that it works smoothly with SQL Server 2000 but fails to work with SQL Server 2005. any suggestions are welcomed.
Reply | Email | Delete | Modify | 
Re: SQL Server 2005 Issue by Muhammad On February 21, 2007

Well it is supposed to work with SQL Server 2005. do you have a detailed information about the error generated?! or there is no error?!

Note:
After some investigation on TransactionScope I do not recommend to use in a none distributed transactions even on SQL SERVER 2005. At least current the release.
TransactionScope is always promoting to Distributed Transaction whenever you open deferent connection.

for example, you have Object A who opens a connection instance, and Object B who opens another connection instance but bother connection instances connect to the same database with the same connection string, This will be promoted to Distributed Transaction, even on SQL SERVER 2005.

I think they will try to enhance this in later releases.

Reply | Email | Delete | Modify | 
mappping of strong name with c sharp class at command prompt by amarjeet On May 22, 2007
mappping of strong name with c sharp class at command prompt and also separating the public key from private key by using command prompt
Reply | Email | Delete | Modify | 
isolation level by amarjeet On May 22, 2007
Readuncommited ,readcommitted,reapetable read,serializable,Snapshot
Reply | Email | Delete | Modify | 
Distributed Transaction Coordinator by Antonio On December 7, 2007
How can Microsoft Distributed Transaction Coordinator span multiple WebForm? Please, contact me at "antonio.vecchio@gmail.com" Regards Antonio
Reply | Email | Delete | Modify | 
Re: Distributed Transaction Coordinator by Anjum On February 5, 2008

I am using transaction Scope with Oracle. It is not woring for me when I configure my application's development server is Local IIS. It does not work.

When I configure to Cassino Server/Asp.net Development Server than it works.

Please can any body explain.

What configuration is required to run TransactionScope with Oracle database. 

 Thank you,

Anjum Rizwi

Reply | Email | Delete | Modify | 
TransactionScope does not work with Asp.net/Oracle by Anjum On February 5, 2008
I am using transaction Scope with Oracle. It is not woring for me when I configure my application's development server is Local IIS. It does not work. When I configure to Cassino Server/Asp.net Development Server than it works. Please can any body explain. What configuration is required to run TransactionScope with Oracle database. Thank you, Anjum Rizwi
Reply | Email | Delete | Modify | 
Delete button is not working. by Anjum On February 5, 2008
I have post my question at wrong place. I tried to delete my question but it does work nor it gives any error.
Reply | Email | Delete | Modify | 
location of transactionScope.Complete() by Rob On February 15, 2008
What happens if you call transactionScope.Complete() after you close the database connections?
Reply | Email | Delete | Modify | 
Re: location of transactionScope.Complete() by Muhammad On February 18, 2008
An exception will be thrown. As you are using a transaction that already ended
Reply | Email | Delete | Modify | 
Re: Re: location of transactionScope.Complete() by Rob On February 19, 2008
That's what I thought too, but in the MSDN documentation (http://tinyurl.com/yo5one) for TransactionScope.Complete(), they do exactly that. They open a transaction scope, then start using two new db connections, and after the connections are closed (via "end using"), the Complete() command is called. I can't wrap my head around how this could possibly work!
Reply | Email | Delete | Modify | 
Transaction Scope in Webservice by Jeeva On May 7, 2009
Hi,

   I am requesting to update certain rows into four tables from UI , also from BL i am updating the different four tables through webservice.

My problem is , if there happens any distraction while updating from BL then the UI transaction also has to be rolled back.

How can i handle this situation using Transaction Scope?

Kindly send me a reply as soon as possible...

Thanks in advance
Jeeva
Reply | Email | Delete | Modify | 
There's an error in this article or maybe a confusion by Jorge On September 30, 2009
Hi all, i found this article interesting but kind of confusing in one part:
//If you did not call the Complete method on the TransactionScope object before its disposal, the transaction manager rolls back the transaction
Well actually, someone can think that if you don't call complete method, it does a rollback action, but this is wrong! if you don't call Complete method, what it does is simply don't call commit action, someone can get confuse, if you want to rollback a transaction you need to write Transaction.Current.Rollback() for example, this is the scenario:
if you insert one row, then insert another row, then you write trx.Complete(); it will commit the transaction and then if you want dispose the trx object.
what you said is ... in the same scenario i didn't write trx.Complete(); it does a rollback?¿ no WAY! as i said it simply didn't commit the transaction.
what is correct is ... in the same scenario, you write complete, and the first row insert successfully and the second row throws a DB exception, and you catch this exception and then you rollback the transaction it will erase the first inserted row and obviously the second row will never be inserted because it was the one that throws the exception.
So please be carefull on what you write in any article because it will get some confusing actions.
Reply | Email | Delete | Modify | 
Re: There's an error in this article or maybe a confusion by Muhammad On September 30, 2009
@jcotillo
What happen if you didn't commit a transaction? Maybe the use of word rollback isn't correct! but at least the result is the same. Because what you did if you didn't call Complete is that all your transaction wan't be committed.

Returning to MSDN here is what is mentioned in the Remarks of Complete Method
"When you are satisfied that all operations within the scope are completed successfully, you should call this method only once to inform that transaction manager that the state across all resources is consistent, and the transaction can be committed. It is very good practice to put the call as the last statement in the using block.
Failing to call this method aborts the transaction, because the transaction manager interprets this as a system failure, or exceptions thrown within the scope of transaction. However, you should also note that calling this method does not guarantee a commit of the transaction. It is merely a way of informing the transaction manager of your status. After calling this method, you can no longer access the ambient transaction via the Current property, and trying to do so results in an exception being thrown."

The above shows that accessing Current after calling complete is not applicable. That means if you didn't call complete that means you wish to rollback your transaction, or actually abort the transaction without committing it. Aren't abort and rollback the same?! then we will reach to the same result.

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.