15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

system.Transactions ❘ 619<br />

it with the connection. Then the Complete() method of the TransactionScope class sets the success bit.<br />

With the end of the using statement, the TransactionScope is disposed, <strong>and</strong> a commit is done. If the<br />

Complete() method is not invoked, the Dispose() method aborts the transaction.<br />

If an ADO.<strong>NET</strong> connection should not enlist with an ambient transaction, you can set<br />

the value Enlist=false with the connection string.<br />

static void TransactionScope()<br />

{<br />

using (var scope = new TransactionScope())<br />

{<br />

Transaction.Current.TransactionCompleted +=<br />

OnTransactionCompleted;<br />

Utilities.DisplayTransactionInformation("Ambient TX created",<br />

Transaction.Current.TransactionInformation);<br />

var s1 = new Student<br />

{<br />

FirstName = "Ingo",<br />

LastName = "Rammer",<br />

Company = "thinktecture"<br />

};<br />

var db = new StudentData();<br />

db.AddStudent(s1);<br />

if (!Utilities.AbortTx())<br />

scope.Complete();<br />

else<br />

Console.WriteLine("transaction will be aborted");<br />

}<br />

} // scope.Dispose()<br />

static void OnTransactionCompleted(object sender, TransactionEventArgs e)<br />

{<br />

Utilities.DisplayTransactionInformation("TX completed",<br />

e.Transaction.TransactionInformation);<br />

}<br />

code snippet TransactionSamples/Program.cs<br />

Running the application, you can see an active ambient transaction after an instance of the<br />

TransactionScope class is created. The last output of the application is the output from<br />

the TransactionCompleted event h<strong>and</strong>ler to display the fi nished transaction state:<br />

Ambient TX created<br />

Creation Time: 9:55:40 PM<br />

Status: Active<br />

Local ID: a06df6fb-7266-435e-b90e-f024f1d6966e:1<br />

Distributed ID: 00000000-0000-0000-0000-0000000000<br />

Abort the Transaction (y/n) n<br />

TX completed<br />

Creation Time: 9:55:40 PM<br />

Status: Committed<br />

Local ID: a06df6fb-7266-435e-b90e-f024f1d6966e:1<br />

Distributed ID: 00000000-0000-0000-0000-0000000000<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!