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()) {
DbProviderFactory provider;
provider = DbProviderFactories.GetFactory("System.Data.SqlClient");
DbConnection conn = provider.CreateConnection();
conn.ConnectionString = strConn;
DbCommand dbcmd = conn.CreateCommand();
dbcmd.Connection = conn;
dbcmd.CommandText = "DELETE Products";
dbcmd.CommandType = CommandType.Text;
DbCommand dbcmd2 = conn.CreateCommand();
dbcmd2.Connection = conn;
dbcmd2.CommandText = "DELETE INVALIDTABLE";
dbcmd2.CommandType = CommandType.Text;
conn.Open();
try {
dbcmd.ExecuteNonQuery();
dbcmd2.ExecuteNonQuery();
ts.Complete();
} catch (DbException ex) {
} finally {
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!