Implementation of Transaction in ASP.NET C#


Today I am going to show you the basics of transaction and some basics of the implementation of transaction.
Now come to the point what is the transaction?
Before go to the definition of the transaction let consider a situation that you are going to transfer $500 from your account to your friends account. Now how it can be done? There are two steps in program
1. Program will deduct $500 from your account
2. Program will add $500 to your friend’s account
Now think after completion of step 1 something bad happen or some error for which step 2 didn’t execute. What will occur?

$500 will be deduced from your account but it will not be added to your friend account. $500 will be missing. I will go mad if something happen. 😦
The formal definition of transaction from book is-
A transaction is a set of operations that must either succeed or fail as a unit. The goal of a transaction is to ensure that data is always in a valid or consistent state.

Transactions help to avoid these types of problems by ensuring that changes are committed to a data source only if all the steps are successful. So, in this example, if step 2 fails, then the changes made by step 1 will not be committed to the database. This ensures that the system stays in one of its two valid states—the initial state (with no money transferred) and the final state (with money debited from one account and credited to another).

Note that even though these are ideal characteristics of a transaction, they aren’t always absolutely attainable. One problem is that in order to ensure isolation, the RDBMS needs to lock data so that other users can’t access it while the transaction is in progress. The more locks you use, and the coarser these locks are, the greater the chance that a user won’t be able to perform another task whiles the transactions are underway. In other words, there’s often a trade-off between user concurrency and isolation.

You can use three basic transaction types in an ASP.NET web application. They are as follows (from least to most overhead):

Stored procedure transactions: These transactions take place entirely in the database. Stored procedure transactions offer the best performance, because they need only a single round-trip to the database. The drawback is that you also need to write the transaction logic using SQL statements (which may be not as easy as using pure C#).
Client-initiated (ADO.NET) transactions: These transactions are controlled programmatically by your ASP.NET web-page code.  Under the covers, they use the same commands as a stored procedure transaction, but your code uses some ADO.NET objects that wrap these details. The drawback is that extra round-trips are required to the database to start and commit the trans- action.
COM+ transactions: These transactions are handled by the COM+ runtime, based on declarative attributes you add to your code.  COM+ transactions use a two-stage commit protocol and always incur extra overhead. They also require that you create a separate serviced component class. COM+ components are generally a good choice only if your transaction spans multiple transaction-aware resource managers, because COM+ includes built-in support for distributed transactions. For example, a single COM+ transaction can span interactions in a SQL Server database and an Oracle database.

Now I am going to show How to implement Transactions easily by stored procedure:
Stored Procedure Transactions
If possible, the best place to put a transaction is in stored procedure code.
Stored procedure is the best place to hold a transaction because the stored procedure (server side code) is always in control which makes it impossible for a client to accidentally hold a transaction open too long and potentially cause problems for other client updates. It also ensures the best possible performance, because all actions can be executed at the data source without requiring any network communication. Generally, the shorter the span of a transaction, the better the concurrency of the database and the fewer the number of database requests that will be serialized (put on hold while a temporary record lock is in place).
Stored procedure code varies depending on the database you are using, but most RDBMSs support the SQL statement BEGIN TRANSACTION. Once you start a transaction, all subsequent statements are considered part of the transaction. You can end the transaction with the COMMIT or ROLLBACK statement. If you don’t, the transaction will be automatically rolled back.

CREATE Procedure TransferAmount
(
@Amount Money
@ID_A int
@ID_B int
)
AS
BEGIN TRANSACTION
UPDATE Accounts SET Balance = Balance + @Amount WHERE AccountID = @ID_A
UPDATE Accounts SET Balance = Balance – @Amount WHERE AccountID = @ID_B
IF (@@ERROR > 0)
ROLLBACK
ELSE
COMMIT

Note: I copped this code from book to make u understand about procedure. But when I tried to run this code in my server I manually cause a problem in 2nd query  (by providing an id of B which actually doesn’t exist)  but it didn’t rollback. I don’t know why?

Here’s an simple example of  implementation of transaction in C#. Here I am using Northwind Database.

string connectionString =
WebConfigurationManager.ConnectionStrings[“Northwind”].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd1 = new SqlCommand(
“INSERT INTO Employees (LastName, FirstName) VALUES (‘Joe’,’Tester’)”);
SqlCommand cmd2 = new SqlCommand(
“INSERT INTO Employees (LastName, FirstName) VALUES                                  (‘Harry’,’Sullivan’)”);
SqlTransaction tran = null;
try
{
// Open the connection and create the transaction.
con.Open();
// Enlist two commands in the transaction.
cmd1.Transaction = tran;
cmd2.Transaction = tran;
// Execute both commands.
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
// Commit the transaction.
tran.Commit();
}
catch
{
// In the case of error, roll back the transaction.
tran.Rollback();
}
finally
{
con.Close();
}

Here is only some basics of implementation of transaction I know.If you got any good material or tutorial on this topic please share link here.

Reference:

Pro ASP.NET  2.0 in C# 2005
Appress &
Internet

Thanks.

Advertisements

About Razib Chandra Deb

I completed my BSc in CSE from CSE Department of KUET. Currently I am working as a Software Engineer in Samsung R&D Institute Bangladesh(SRBD). I am interested in image processing.
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

6 Responses to Implementation of Transaction in ASP.NET C#

  1. Abby says:

    Hello Razib a great Article….
    I have a transaction set up in my stored Procedure which is working fine in Sql Server 2008. I want to fire it from my C# code.How do i do it . If it works it proceeds or else it should give an error in my application.

  2. dear,
    can you tell me that after commit of trans ..how can i redirect a another page?
    if our trans is success.
    and else our trans will not succes then how can we provide a error msg?

  3. Deepak verma says:

    very good and simple article ………. its working fine …thanks dud

  4. thank you razibdeb for your simple article.

  5. jithin says:

    Thanks for giving us a good article .. which is the best way to define a transaction ( public or private ) ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s