System.Transactions Namespace

Posted Monday, January 10, 2005 9:13 AM by C-Dog's .NET Tip of the Day
There is probably more interest for this on the web services side, since we rarely do that much direct access to a database.  Framework v2.0 makes it really easy to handle transactions.  Transactions make it possible to roll back a series of SQL statements, etc when any one of the statements fail.
 
There are two types of transcations that you will typically deal with Local Implicit and Distributed Implicit (note: there are also Explicit transactions but they seem to be a lot more work and not as convenient.)  A Local Implicit transaction is simply a transaction that talks to only one database.  A Distributed transaction talks to multiple databases at the same time. 
 
The transactions namespace is smart and will automatically use the appropriate transaction broker based on what type of database you are using.  If you are talking to SQL Server 2000 databases, the transactions will be handled through the DTC on the client machine.  When SQL Server 2005 is used, the transactions are handled directly by the SQL Server.
 
Creating a transaction is easy.  Simply create a TransactionScope with a using statement and include your code to execute your sql statements.  When the transaction is complete, tell the TransactionScope, that the commit is ready by setting the Consistent property to true (Note: this property is replaced by the Complete() method in Beta 2).
 
Here is an example of a distributed transaction:
 
using (TransactionScope transactionScope = new TransactionScope())
{
     // create a SqlConnection
     SqlConnection sqlConnection1 = new SqlConnection(connectionString1);
 
     // create a new sqlCommand
     SqlCommand sqlCommand1 = new SqlCommand(someQuery, sqlConnection1);
 
     // open the first connection
     SqlConnection1.Open();
 
     // execute the query
     SqlConnection1.ExecuteNonQuery();
 
     // close the connection
     SqlConnection1.Close();
 
     // open a connection to a second sql server database
 
     // create a SqlConnection
     SqlConnection sqlConnection2 = new SqlConnection(connectionString2);
 
     // create a new sqlCommand
     SqlCommand sqlCommand2 = new SqlCommand(someQuery, sqlConnection2);
 
     // open the first connection
     SqlConnection2.Open();
 
     // execute the query
     SqlConnection2.ExecuteNonQuery();
 
     // close the connection
     SqlConnection2.Close();
 
 
     // tell the scope that the transaction is complete
     transactionScope.Consitent = true;
}
 
The basics of transactions are really quite easy now.  No longer do you have to worry about using Reflection or deriving from ServiceComponent.  This should prove to be quite useful in the future.

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=202