IT Community - Software Programming, Web Development and Technical Support

Transaction Scope in DotNet using C#.

This is a discussion on Transaction Scope in DotNet using C#. within the C# Programming forums, part of the Software Development category; Hi Friends, From this thread I'm going to explain how to use Transaction Scope in C# and what the ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Software Development > C# Programming

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 09-01-2007, 12:49 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Transaction Scope in DotNet using C#.

Hi Friends,

From this thread I'm going to explain how to use Transaction Scope in C# and what the purpose of Transaction Scope.

Learn with my threads and share your knowledge here....
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 09-01-2007, 12:53 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

System.Transactions

The .NET 2.0 Framework introduces a new namespace called System.Transactions that makes transactional programming easier when dealing with ADO.NET, Sql Server, MSMQ, and the Microsoft Distributed Transaction Coordinator (MSDTC).

I came across some code that was using System.Transactions to handle local transactions connecting to Sql Server. The code was essentially like this:
Code:
using (TransactionScope scope =
    new TransactionScope())
{
    using (SqlConnection connection =
        new SqlConnection(connectionString))
    {
        SqlCommand command = connection.CreateCommand();
        command.CommandText = "Insert....";
        
        SqlCommand command2 = connection.CreateCommand();
        command.CommandText = "Update....";

        connection.Open();
        command.ExecuteNonQuery();
        command2.ExecuteNonQuery():
        connection.Close();
    }

    scope.Complete();
}
Certainly you can use System.Transactions for local transactions, but it backfires on you with Sql Server .

If you are using Sql Server 2000, the local transaction automatically becomes promoted to a distributed transaction managed by MSDTC, which is unecessary in this case and will cause a performance hit. Sql Server 2000 does not support “promotable transactions,“ which is needed to take advantage of the Lightweight Transaction Manager.

I'm still using SqlTransaction for all local database transactions, although I certainly love the code simplicity of using System.Transactions and TransactionScope.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 09-01-2007, 01:05 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

Anyway, I thought I would share some basic information about SQL Server Transactions from this thread for those who are new to ADO.NET.

This thread does a good job of providing an overview of transactions and a basic template for how to execute local transactions in code.

Here is the basic template for an ADO.NET 2.0 Transaction:

Code:
using (SqlConnection connection =
            new SqlConnection(connectionString))
{
    SqlCommand command = connection.CreateCommand();
    SqlTransaction transaction = null;
    
    try
    {
        // BeginTransaction() Requires Open Connection
        connection.Open();
        
        transaction = connection.BeginTransaction();
        
        // Assign Transaction to Command
        command.Transaction = transaction;
        
        // Execute 1st Command
        command.CommandText = "Insert ...";
        command.ExecuteNonQuery();
        
        // Execute 2nd Command
        command.CommandText = "Update...";
        command.ExecuteNonQuery();
        
        transaction.Commit();
    }
    catch
    {
        transaction.Rollback();
        throw;
    }
    finally
    {
        connection.Close();
    }
}
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 09-01-2007, 01:19 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

A c# using statement wraps up the connection, because SqlConnection implements IDisposable. The using statement makes sure that Dispose() gets called on the connection object so it can free up any unmanaged resources.

Before you can begin a transaction, you must first open the connection. You begin your transaction and then assign any newly created command objects to that transaction and perform queries as necessary. Commit the transaction. If an error occurs, Rollback the transaction in a catch statement to void out any changes and then rethrow the error so that the application can deal with it accordingly.

The connection is properly closed in the finally statement, which gets called no matter what, and any unmanaged resources are disposed when the using statement calls Dispose() on the connection.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 09-01-2007, 01:21 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

The above template could actually implement a second c# using statement around command, because SqlCommand also implements IDisposable. I don't know that it is really necessary, however. I just like to see using statements around anything that implements IDisposable:

Code:
using (SqlConnection connection = new SqlConnection(connectionString))
{
    using (SqlCommand command =
            connection.CreateCommand())
    {
        SqlTransaction transaction = null;
        
        try
        {
            // BeginTransaction() Requires Open Connection
            connection.Open();
            
            transaction = connection.BeginTransaction();
            
            // Assign Transaction to Command
            command.Transaction = transaction;
            
            // Execute 1st Command
            command.CommandText = "Insert ...";
            command.ExecuteNonQuery();
            
            // Execute 2nd Command
            command.CommandText = "Update...";
            command.ExecuteNonQuery();
            
            transaction.Commit();
        }
        catch
        {
            transaction.Rollback();
            throw;
        }
        finally
        {
            connection.Close();
        }
    }
}
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 09-01-2007, 04:00 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

SQL Server Transaction Savepoints

In the last post I talked about the basics of SQL Server Transactions. There is also a small section on SQL Server Savepoints, which is the ability to mark points within the life of your transaction in the case that you may only want to rollback the current transaction to a specific point as opposed to the very beginning.

Savepoints give you the flexibility to only roll back and commit portions of a SQL Server Transaction as opposed to rolling back the entire transaction. One may not need the functionality often, but it is nice to know savepoints exist when the time comes.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 09-01-2007, 04:03 AM
Mramesh Mramesh is offline
D-Web Sr.Programmer
 
Join Date: Sep 2007
Location: Chennai
Posts: 106
Mramesh is on a distinguished road
Send a message via MSN to Mramesh
Smile Re: Transaction Scope in DotNet using C#.

Savepoints offer a mechanism to roll back portions of transactions. A user can set a savepoint, or marker, within a transaction.

The savepoint defines a location to which a transaction can return if part of the transaction is conditionally canceled. SQL Server allows you to use savepoints via the SAVE TRAN statement.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 09-02-2007, 10:28 PM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

If you look at a snippet of the SQL Server Transaction Template presented in my previous post, you can notice the transaction.Rollback() statement in the catch block that rolls back the entire transaction when an unexpected exception is thrown,

Code:
try
{
    // ...
    transaction.Commit();
}
catch
{
    transaction.Rollback();
    throw;
}
finally
{
    connection.Close();
}
I'm going to explain about those two methods in my upcoming posts....
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 09-02-2007, 10:30 PM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

Yes...

Here is SqlTransaction.Rollback and SqlTransaction.Save Methods

The SqlTransaction Rollback method has an overload that will accept the name of a Savepoint if you would rather just roll the transaction back to a specific Savepoint as opposed to rolling back the entire transaction:

Code:
transaction.Rollback("FirstUpdate");
As you would expect, the SqlTransaction Class also has a method, called Save, that allows you to create a Savepoint in the life of the transaction:

Code:
transaction.Save("FirstUpdate");
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 09-02-2007, 10:32 PM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

Example of SqlTransaction.Rollback and SqlTransaction.Save

Using both the Rollback and Save methods in SqlTransaction to partially rollback a transaction would look something like below. Of course, rather than just rolling back for kicks, a real application would have some business logic for doing so:

Code:
using (SqlConnection connection =
        new SqlConnection(connectionString))
{
    using (SqlCommand command =
        connection.CreateCommand())
    {
        connection.Open();
            
        SqlTransaction transaction =
                connection.BeginTransaction();
        
        command.Transaction = transaction;
        
        try
        {
            command.CommandText = "Update...";
            command.ExecuteNonQuery();
            
            // Create a Savepoint
            transaction.Save("FirstUpdate");
            
            command.CommandText = "Insert...";
            command.ExecuteNonQuery();
            
            // Rollback to FirstUpdate
            transaction.Rollback("FirstUpdate");
            
            transaction.Commit();
        }
        catch
        {
            transaction.Rollback();
            throw;
        }
        finally
        {
            connection.Close();
        }
    }
}
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 09-04-2007, 12:02 AM
Mramesh Mramesh is offline
D-Web Sr.Programmer
 
Join Date: Sep 2007
Location: Chennai
Posts: 106
Mramesh is on a distinguished road
Send a message via MSN to Mramesh
Default Re: Transaction Scope in DotNet using C#.

Hi all,

I would like to use TransactionScope within the Business Layer of
my web application.
Is any Idea?
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 09-04-2007, 12:13 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

Hi,

it should not be used in a shared web hosting environment because the server may get
re-configured.


I don't see how the server becoming reconfigured affects the use of
TransactionScope.

You want to use the TransactionScope class when you want the code
encapsulated in the scope of the instance (it's meant to be used in a using
statement) is to run in a transactional context.

Look at the documentation for the TransactionScope class on how to use
it.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 09-04-2007, 12:19 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

Actually, TransactionScope is supposed to work even if DTC is
disabled/uninstalled, as long as you don't do anything that causes
promotion.

only MS SqlServer 2005 supports promotable transactions.
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #14 (permalink)  
Old 09-04-2007, 12:42 AM
krishnakumar krishnakumar is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 206
krishnakumar is on a distinguished road
Smile Re: Transaction Scope in DotNet using C#.

Hi,
The Following Notes will clear u...

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.
__________________
Krishnakumar.S
Beware of Everything -that is un true; stick to the Truth shall succeed slowly but steadily
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #15 (permalink)  
Old 09-04-2007, 12:48 AM
S.Vinothkumar S.Vinothkumar is offline
D-Web Genius
 
Join Date: May 2007
Posts: 1,061
S.Vinothkumar is on a distinguished road
Wink Re: Transaction Scope in DotNet using C#.

TransactionScope Class

This class is new in the .NET Framework version 2.0.

Makes a code block transactional. This class cannot be inherited.

For more see TransactionScope Class in msdn.....
__________________
S.VinothkumaR
Behind me is infinite power,
Before me is Endless Possibility,
Around me is Boundless Opportunity,
Why should I fear!
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #16 (permalink)  
Old 09-04-2007, 01:28 AM
H2o H2o is offline
D-Web Analyst
 
Join Date: Jul 2007
Posts: 246
H2o is on a distinguished road
Question Re: Transaction Scope in DotNet using C#.

Hi,

how to Create Distributed Transaction?

Can u explain programmatically?
__________________
H2O

Without us, no one can survive..
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #17 (permalink)  
Old 09-04-2007, 01:33 AM
amansundar amansundar is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 325
amansundar is on a distinguished road
Default Re: Transaction Scope in DotNet using C#.

Hi all,

I'm getting the following error when I use the TransactionScope in my coding....

Error: Communication with the underlying transaction manager has failed

I don't know where I'm doing mistake.....

This is where the error happens...

public void insertDB()
{
SqlConnection Conn = new SqlConnection(connectionString);
Conn.Open();
SqlTransaction sqltran = Conn.BeginTransaction();
SqlCommand cmd = new SqlCommand(statementString, Conn, sqltran);
cmd.ExecuteNonQuery();
sqltran.Commit();
}

I'm calling the insert here ....
private void InsertCustomerToDB(object sender, EventArgs e)
{
using (TransactionScope scope = new TransactionScope())
{
int BillingID = insertDB();
int DeliveryID = insertDB();

int CustomerID = DBTrip.CustomerAdapter.InsertContact(CustomerInfo) ;
}
}
__________________
cheers
Aman
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #18 (permalink)  
Old 09-04-2007, 03:32 AM
raja raja is offline
D-Web Trainee
 
Join Date: May 2007
Posts: 34
raja is on a distinguished road
Cool Re: Transaction Scope in DotNet using C#.

Hi AMan,

I found the solution for ur probs....


In ur calling method you have to open the conneciion by the transaction scope and keep it open while prforming the different insert methods.

Another thing you have to do is pass the Conn to the method where you will be using it.

in the method you will have to accept the passed connection with InsertContact(SqlConnection Conn)


Change ur code as follows,


Code:
private void InsertCustomerToDB(object sender, EventArgs e)

{

using (TransactionScope scope = new TransactionScope())

{
 Conn.Open();

 int BillingID = insertDB();

 int DeliveryID = insertDB();
 
 int CustomerID = DBTrip.CustomerAdapter.InsertContact(CustomerInfo);
 
 Conn.Close();

 scope.Complete();

}

}
__________________
Raja. Myblog
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #19 (permalink)  
Old 09-04-2007, 04:17 AM
amansundar amansundar is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 325
amansundar is on a distinguished road
Default Re: Transaction Scope in DotNet using C#.

its working fine....thank u for your response raja
__________________
cheers
Aman
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #20 (permalink)  
Old 09-04-2007, 06:19 AM
mobilegeek mobilegeek is offline
D-Web Analyst
 
Join Date: Jun 2007
Posts: 205
mobilegeek is on a distinguished road
Question Re: Transaction Scope in DotNet using C#.

When appling Transaction scope to handle transaction, it seems that the transaction manager will make use Distrbuted Trsnsaction Coordinator to manage the transaction.

However, with using DTC, will it be more expensive than using ADO.Net transaction Object ? And also, will the performance affect by the network traffic?
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
scope variable itbarota HTML, CSS and Javascript Coding Techniques 1 11-13-2007 12:29 AM
What is Ngen.exe in DotNet? leoraja8