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!

You might also like...

Comments

Xavier Larrea

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Beware of bugs in the above code; I have only proved it correct, not tried it.” - Donald Knuth