Labels

Thursday, January 14, 2010

Transaction using TransactionScope

The System.Transactions infrastructure provides both an explicit programming model based on the Transaction class, as well as an implicit programming model using the TransactionScope class, in which transactions are automatically managed by the infrastructure.

 

Upon instantiating a TransactionScope by the new statement, the transaction manager determines which transaction to participate in. Once determined, the scope always participates in that transaction. The decision is based on two factors: whether an ambient transaction is present and the value of the TransactionScopeOption parameter in the constructor. The ambient transaction is the transaction your code executes in. You can obtain a reference to the ambient transaction by calling the static Current property of the Transaction class. For more information on how this parameter is used, please see the "Transaction Flow Management" section of the Implementing an Implicit Transaction using Transaction Scope topic.

 

If no exception occurs within the transaction scope (that is, between the initialization of the TransactionScope object and the calling of its Dispose method), then the transaction in which the scope participates is allowed to proceed. If an exception does occur within the transaction scope, the transaction in which it participates will be rolled back.

 

When your application completes all work it wants to perform in a transaction, you should call the Complete method only once to inform that transaction manager that it is acceptable to Commit the transaction. Failing to call this method Aborts the transaction.

 

A call to the Dispose method marks the end of the transaction scope. Exceptions that occur after calling this method may not affect the transaction.

 

If you modify the value of Current inside a scope, an exception is thrown when Dispose is called. However, at the end of the scope, the previous value is restored. In addition, if you call Dispose on Current inside a transaction scope that created the transaction, the transaction aborts at the end of the scope.

 

static public int CreateTransactionScope(string connectString1, string connectString2, string commandText1, string commandText2)

{

    // Initialize the return value to zero and create a StringWriter to display results.

    int returnValue = 0;

    System.IO.StringWriter writer = new System.IO.StringWriter();

 

    try

    {

        // Create the TransactionScope to execute the commands, guaranteeing

        // that both commands can commit or roll back as a single unit of work.

        using (TransactionScope scope = new TransactionScope())

        {

            using (SqlConnection connection1 = new SqlConnection(connectString1))

            {

                // Opening the connection automatically enlists it in the TransactionScope as a lightweight transaction.

                connection1.Open();

 

                SqlCommand command1 = new SqlCommand(commandText1, connection1);

                returnValue = command1.ExecuteNonQuery();

                writer.WriteLine("Rows to be affected by command1: {0}", returnValue);

 

                // If you get here, this means that command1 succeeded. By nesting

                // the using block for connection2 inside that of connection1, you

                // conserve server and network resources as connection2 is opened

                // only when there is a chance that the transaction can commit.  

                using (SqlConnection connection2 = new SqlConnection(connectString2))

                {

                    // The transaction is escalated to a full distributed

                    // transaction when connection2 is opened.

                    connection2.Open();

 

                    // Execute the second command in the second database.

                    returnValue = 0;

                    SqlCommand command2 = new SqlCommand(commandText2, connection2);

                    returnValue = command2.ExecuteNonQuery();

                    writer.WriteLine("Rows to be affected by command2: {0}", returnValue);

                }

            }

        }

 

        // The Complete method commits the transaction. If an exception has been thrown,

        // Complete is not  called and the transaction is rolled back.

        scope.Complete();

    }

    catch (TransactionAbortedException ex)

    {

        writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);

    }

    catch (ApplicationException ex)

    {

        writer.WriteLine("ApplicationException Message: {0}", ex.Message);

    }

 

    // Display messages.

    Console.WriteLine(writer.ToString());

 

    return returnValue;

}

 

Hope this helps.

 

Regards,

Arun Manglick



Disclaimer: The information contained in this message may be privileged, confidential, and protected from disclosure. If you are not the intended recipient, or an employee, or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication is strictly prohibited. If you have received this communication in error, please notify us immediately by replying to the message and deleting it from your computer.

No comments:

Post a Comment