Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press
Buy directly from Paradoxal Press at $33.99 (Save 43%)
Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA
|
Listing 20-4 extracted from chapter Transactions
Listing 20-3< > Listing 20-5
This listing can be compiled with the command line: csc.exe /target:exe Example_20_4.cs /r:System.Transactions.dll Errors: 0 Warnings: 0
Example_20_4.cs
using System.Data.Common;
using System.Data.SqlClient;
using System.Transactions;
class Program {
static void Main() {
string sCnx1 =
"server = localhost ; uid=sa ; pwd =; database = ORGANIZATION";
string sCnx2 =
"server = localhost ; uid=sa ; pwd =; database = ORGANIZATION2";
string sCmd1 =
"DELETE FROM EMPLOYEES WHERE Surname='Smith' AND Firstname='Adam'";
string sCmd2 =
"INSERT INTO EMPLOYEES VALUES ('COM','Smith','Adam','(123) 456-7899')";
try {
using ( TransactionScope txScope = new TransactionScope() ) {
Transaction.Current.TransactionCompleted += OnTxCompleted;
TransactionManager.DistributedTransactionStarted +=
OnDistributedTxStarted;
using ( SqlConnection cnx1 = new SqlConnection(sCnx1) ) {
cnx1.Open();
DbCommand cmd = new SqlCommand(sCmd1, cnx1);
cmd.ExecuteNonQuery();
} // end using cnx1.
using (SqlConnection cnx2 = new SqlConnection(sCnx2)) {
cnx2.Open();
DbCommand cmd = new SqlCommand(sCmd2, cnx2);
cmd.ExecuteNonQuery();
} // end using cnx1.
txScope.Complete();
} // end using txScope, the transaction terminates here.
} catch { }
}
static void OnTxCompleted(object sender, TransactionEventArgs e) {
Transaction tx = e.Transaction;
System.Console.WriteLine("Completed! Status:" +
tx.TransactionInformation.Status.ToString());
}
static void OnDistributedTxStarted(object sender,
TransactionEventArgs e) {
Transaction tx = e.Transaction;
System.Console.WriteLine("Distributed tx started!");
}
}
Copyright Patrick Smacchia 2006 2007
|