Monday, November 17, 2014

TransactionScope in ASP.NET

This is one of the good feature which will help you when you have to do multiple database operations and you wanted to make sure that all the transaction has to be either committed or roll backed as a single unit of work.
TransactionScope is exactly same as the one we use in database level. But sometimes we may not use transaction at database level if the data/table we are operating is completely different and there is no connections.
Couple of important points you have to remember while using TransactionScope is, TransactionScope class cannot be inherited, also this is part of the System.Transactions which means if you wanted to use the class TransactionScope then first you have to refer to the assembly System.Transactions.

Now lets see the sample code,

try

{

using (TransactionScope TranScope = new TransactionScope())

{

DataSet dsBalance = GetCustomerBalance();

//Other operations goes here

DataSet dsWithdrawal = CommitWithdrawal();

//Other operations goes here

TranScope.Complete();

}

}

catch (TransactionAbortedException ex)

{

lblMsg.Text = "Error While procesing the data " + ex.Message;

}

catch (ApplicationException ex)

{

lblMsg.Text = "Error While procesing the data " + ex.Message;

}

Lets go through line by line. I have put the complete code inside the try block because I will be able to catch the exception separately. In this case I have two catch blocks one for TransactionAbortedException and another for ApplicationException.
After try and catch block what we have to do is, start a TransactionScope area where you can keep all your commands to be executed as a single unit of work. In normal scenario you have to even open the database connection inside this TransactionScope.
Once all the codes are executed inside the TransactionScope then the last command to be executed is the Complete method. Once you execute Complete method then the whole transaction will be committed. If you have any exception in any of the methods then complete method will not be called and your transaction will be rolled back.
I hope you are now clear on how to use TransactionScope in ASP.NET.
Happy coding!!!