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.

summary ❘ 635<br />

txH<strong>and</strong>le, IntPtr.Zero, IntPtr.Zero);<br />

}<br />

}<br />

}<br />

return new FileStream(fileH<strong>and</strong>le, FileAccess.Write);<br />

code snippet FileSystemTransactions/TransactedFile.cs<br />

Now it is very easy to use the transactional API from .<strong>NET</strong> code. You can create an ambient transaction<br />

with the TransactionScope class <strong>and</strong> use the TransactedFile class within the context of the ambient<br />

transaction scope. If the transaction is aborted, the file is not written. If the transaction is committed, you<br />

can find the file in the temp directory:<br />

using System;<br />

using System.IO;<br />

using System.Transactions;<br />

namespace Wrox.ProCSharp.Transactions<br />

{<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

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

{<br />

FileStream stream = TransactedFile.GetTransactedFileStream(<br />

"sample.txt");<br />

var writer = new StreamWriter(stream);<br />

writer.WriteLine("Write a transactional file");<br />

writer.Close();<br />

}<br />

}<br />

}<br />

}<br />

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

scope.Complete();<br />

code snippet Windows7Transactions/Program.cs<br />

Now you can use databases, volatile resources, <strong>and</strong> files within the same transaction.<br />

summary<br />

In this chapter, you learned the attributes of transactions <strong>and</strong> how you can create <strong>and</strong> manage transactions<br />

with the classes from the System.Transactions namespace.<br />

Transactions are described with ACID properties: atomicity, consistency, isolation, <strong>and</strong> durability. Not all<br />

these properties are always required, as you have seen with volatile resources that don’t support durability<br />

but have isolation options.<br />

The easiest way to deal with transactions is by creating ambient transactions <strong>and</strong> using the<br />

TransactionScope class. Ambient transactions are very useful working with the ADO.<strong>NET</strong> data adapter<br />

<strong>and</strong> the ADO.<strong>NET</strong> Entity Framework, where usually you do not open <strong>and</strong> close database connections<br />

explicitly. ADO.<strong>NET</strong> is covered in Chapter 30, “Core ADO.<strong>NET</strong>.” Entity Framework is explained in<br />

Chapter 31, “ADO.<strong>NET</strong> Entity Framework.”<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!