Library code snippets

Transactions made easy with .NET 2.0

One of the more significant improvement in .NET 2.0 is the transactions area. Now with a single line it becomes extremely easy to support transactional code blocks using the concept of “ambient” transaction thanks to TransactionScope in the System.Transactions namespace.

Check out the following code:

using (TransactionScope ts = new TransactionScope()) {

// An "ambient" transaction is placed in the current call context
DbProviderFactory provider;
provider = DbProviderFactories.GetFactory("System.Data.SqlClient");
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = strConn;

// First query. This one will succeed.
DbCommand dbcmd = conn.CreateCommand();
dbcmd.Connection = conn;
dbcmd.CommandText = "DELETE Products";
dbcmd.CommandType = CommandType.Text;

// Second query. This one will fail.
DbCommand dbcmd2 = conn.CreateCommand();
dbcmd2.Connection = conn;
dbcmd2.CommandText = "DELETE INVALIDTABLE";
dbcmd2.CommandType = CommandType.Text;

conn.Open();

try {
// Let's empty the Products table using the query #1.
dbcmd.ExecuteNonQuery();
// The second query will try to empty a non-existent table.
// It will fail and the ts.Complete() method wont be executed.

dbcmd2.ExecuteNonQuery();
//If all the operations succeded,
//then let's commit the transaction.

ts.Complete();

} catch (DbException ex) {

// Error handling block

} finally {

// Cleanup
conn.Close();
ts.Dispose();
}
}

Extremely simple, isn't it? TransactionScope will take care of almost all the transactional stuff in this code block. All that is required to commit the transaction is to call the ts.Complete() method. Notice that the connection object itself is confined within the scope so it automatically participates in the transaction.

You can manipulate the transaction context with Transaction.Current. Please be aware that this is not limited to SQL Server operations. You can create transaction for Oracle, SQL Server data-storages, MSMQ messaging and even bulk copying filesystem operations.

I hope you found this article useful. Happy coding!

Comments

  1. 01 Jan 1999 at 00:00

    This thread is for discussions of Transactions made easy with .NET 2.0 .

Leave a comment

Sign in or Join us (it's free).

Xavier Larrea
AddThis

Related podcasts

Events coming up

  • Nov 18

    15 Minutes of Fame

    Dresher, United States

    This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.

Want to stay in touch with what's going on? Follow us on twitter!