Friday, September 12, 2008

How to know Transaction Is Successful

Based on .Net Framework, it is convient to use transaction with System.Transactions.TransactionScope class. If no error occurs in the transaction scope, the TransactionScope object will complet, otherwise rollback.

In some situations, we need execute some business logics after transaction complet successfully. Note that we don’t add some business logic code lines after complet() method. In another word, we must place these business logics out of the transaction scope. However, the transaction object had been disposed out of using statement. So, how to know the transaction is successful?

Transaction object exposes the event called TransactionCompleted and provides TransactionStatus which is enumeration type. TransactionStatus enumeration type includes four values: Aborted, Committed, Active and InDoubt. Then we can make a decision depending on the value of TransactionStatus which is belong to TransactionInformation object. TransactionInformation object is a property of Transaction instance.

The sample code is as below:

using (TransactionScope ts = new TransactionScope())

{

    Transaction transaction = Transaction.Current;

    transaction.TransactionCompleted += pro.OnCompleted;

    pro.UpdateEmployee();

    pro.DeleteCustomer();

    ts.Complete();          

}

 

void OnCompleted(object sender, TransactionEventArgs e)

{

    Debug.Assert(sender.GetType() == typeof(Transaction));

    Debug.Assert(object.ReferenceEquals(sender,e.Transaction));

    Transaction transaction = e.Transaction;

    switch (transaction.TransactionInformation.Status)

    {

        case TransactionStatus.Aborted:

            m_TransactionCommitted = false;

            //Not to do something when failed

            break;

        case TransactionStatus.Committed:

            m_TransactionCommitted = true;

            //do something when success

            break;

        default:

            m_TransactionCommitted = false;

            break;

    }

}

No comments: