Click here to Skip to main content
6,634,665 members and growing! (16,633 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » .NET Framework » General     Intermediate

Implementing TransactionScope Using .Net 2.0

By Chandrashekhar Kulkarni

An overview of TransactionScope feature in .net 2.0
C# 2.0, Windows, .NET 2.0VS2005, Dev
Posted:29 May 2007
Views:31,018
Bookmarked:9 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
9 votes for this article.
Popularity: 1.43 Rating: 1.50 out of 5
7 votes, 77.8%
1
1 vote, 11.1%
2

3

4
1 vote, 11.1%
5

Introduction and Background

In earlier development tools, the database transaction management was an isolated topic that required separate thought process. Considering the example of heterogeneous production and development environment where the application is interacting with multiple databases, transaction management was tedious task.

Several legacy systems are on the verge of migration; however, these legacy systems have a serious constraint from back-end point of view. Due to the business risks involved database migration is usually considered as a separate project. Also, real time applications cannot take the risk of downtime in the production environment due to business constrains.

Under such circumstances, application enhancement or new supplementary automations are required to communicate with legacy database and other latest databases as well. This interaction, several times is observed to be a transaction based interaction.

New release of Microsoft .net 2.0 resolves this issue with a new feature called as the "Transaction Scope". In this article, we will discuss in brief the overview of this feature.

This article requires prior knowledge of database Transaction implementation.

Agenda

1.Transaction Options
2.TransactionScope Options
3.Transaction Scope
4.Transaction Promotion
5. Conclusion

Then lets start here....

Transaction Options

What is Transaction Option?

  • Encapsulates the timeout and isolation level parameters for a transaction into a single, simple structure.
  • Passed to the TransactionScope constructors to create a new transaction with the desired behaviors.

Usage Notes

  • Specify Isolation Level using enums -
      • Chaos
      • ReadCommitted
      • ReadUncommitted
      • RepeatableRead
      • Serializable
      • Unspecifie
  • Specify Timeout -Timeout period for the transaction.
  • Parameter to TransactionScope -Once the Options Object is ready, pass it on to the TransactionScope.

Implementation

TransactionOptions TransOpt = New TransactionOptions();
TransOpt.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; 
TransOpt.Timeout = New TimeSpan(0, 2, 0);

TransactionScope Options


What is TransactionScope Option?

  • Define behavior and scope of transaction scope.
  • Defines behavior of ambient transaction.
  • Start, Re-Use or ignore current transaction context.

Usage Notes

  • Required - Transaction MUST present and re-use if already exists.
  • RequiresNew - Transaction MUST present and always create a new transaction.
  • Suppres- Transaction should not be used, even if exists.


Implementation

using(TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TransOptions))
using(TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, TransOptions))
using(TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress, TransOptions))

TransactionScope


What is TransactionScope ?

  • 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.
  • If multiple data sources are accessed in same context, then ENLISTED transactions are promoted to DTC.


Usage Notes

  • Define Scope
  • Connect one data source
  • Connect another data source
  • Manipulate data
  • On success, Set complete flag to true
  • Close the scope

Implementation

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
{
string strCmd = "SQL to Execute";
conn = new SqlClient.SqlConnection("Connection to DB1");
conn.Open()
objCmd = new SqlClient.SqlCommand(strCmd, conn);
objCmd.ExecuteNonQuery();
string strCmd2 = "SQL to Execute";
conn2 = new SqlClient.SqlConnection("Connection to DB2");
conn2.Open()
objCmd2 = new SqlClient.SqlCommand(strCmd2, conn2);
objCmd2.ExecuteNonQuery();
}

Transaction Promotion

Lightweight Transaction

  • A Lightweight Transaction remains with single data source.
  • Lightweight Transactions enable you to incorporate several distinct operations, which occur on single systems, into an atomic action that either succeeds or fails completely.
  • Lightweight Transactions are managed by LTM i.e. Lightweight Transaction Manager.

Screenshot - SingleDatabase.gif


Distributed Transaction

  • 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.
  • Distributed Transactions are managed by DTC i.e. Distributed Transaction Coordinator.

Screenshot - MultiDatabase.gif


DTC Promotion

  • In a defined TransactionScope, if multiple connection are placed to different data sources, the Enlisted Lightweight Transactions are handed over to DTC from LTM.
  • This has no impact on application and requires no special configuration.
  • This can be monitored using SQL Server Profiler 2005.


Conclusion

  • Transaction Management in "Multiple Data Source" scenario is no more issue.
  • Completely ACID Transaction with multiple data sources without any additional overhead to application.
  • Extremely powerful feature in .net 2.0.

Further Readings:

http://msdn.microsoft.com/msdnmag/issues/06/11/DataPoints/default.aspx

http://msdn2.microsoft.com/en-us/library/system.transactions.transactionscope.aspx

http://msdn2.microsoft.com/en-us/library/system.transactions.transactionscopeoption.aspx

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Chandrashekhar Kulkarni


Member
Web Development:
.Net 2.0, VB.net, ASP.net, Classic ASP, VBScript, Javascript, HTML, DHTML,

OpenSource:
Perl, PHP, Linux, Apache, IIS.

Desktop Developement:
VB.net, VB 6, COM/DCOM, Winsock, MAPI, CDO, Outlook Object Model, LDAP, C, C++, Foxpro 2.5, Clipper.

Database:
MS SQL - Server, MySQL, PostgreSQL

Other:
Enterprise Architect, Microsoft Project, Rational Rose, UML.

Has Nine+ years of experience with IT and now working in Project Manager's Role.
Occupation: Web Developer
Location: India India

Other popular .NET Framework articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 16 of 16 (Total in Forum: 16) (Refresh)FirstPrevNext
GeneralMy vote of 1 PinmemberBorginer18:47 9 Nov '09  
Generalread data application get timeout, when updating take long time. PinmemberMember 15263728:08 4 Jun '08  
JokeExcellent Articale for PinmemberViju Khote11:02 14 Dec '07  
GeneralRe: Excellent Articale for PinmemberChandrashekhar Kulkarni1:48 4 Jan '08  
GeneralForgot the Complete(); PinmemberCasper Leon Nielsen3:47 12 Nov '07  
GeneralRe: Forgot the Complete(); PinmemberChandrashekhar Kulkarni4:33 14 Nov '07  
QuestionTransaction Scope in DAL or BLL? [modified] Pinmemberblooper0217:40 10 Oct '07  
AnswerRe: Transaction Scope in DAL or BLL? PinmemberChandrashekhar Kulkarni6:51 21 Oct '07  
GeneralRe: Transaction Scope in DAL or BLL? Pinmemberblooper0216:21 21 Oct '07  
GeneralRe: Transaction Scope in DAL or BLL? PinmemberTvdHeuvel17:15 8 Sep '08  
GeneralRe: Transaction Scope in DAL or BLL? Pinmemberblooper0218:37 8 Sep '08  
QuestionLDAP transaction Pinmemberinew19:39 24 Aug '07  
QuestionAny suggestion on how to do explicit rollback? Pinmemberbhuvan0117:54 5 Jun '07  
AnswerRe: Any suggestion on how to do explicit rollback? PinmemberPITRep12:40 7 Jun '07  
GeneralRe: Any suggestion on how to do explicit rollback? Pinmembermousedoc19:04 7 Jun '07  
GeneralRe: Any suggestion on how to do explicit rollback? PinmemberChandrashekhar Kulkarni23:44 7 Jun '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 29 May 2007
Editor:
Copyright 2007 by Chandrashekhar Kulkarni
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project