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.

Custom resource Managers ❘ 631<br />

}<br />

}<br />

}<br />

public void Commit(Enlistment enlistment)<br />

{<br />

parent.Commit(Value, currentTransaction);<br />

enlistment.Done();<br />

}<br />

public void Rollback(Enlistment enlistment)<br />

{<br />

parent.Rollback(currentTransaction);<br />

enlistment.Done();<br />

}<br />

public void InDoubt(Enlistment enlistment)<br />

{<br />

enlistment.Done();<br />

}<br />

The class Transactional can now be used to make non-transactional classes transactional — for<br />

example, int <strong>and</strong> string but also more complex classes such as Student — as long as the type is<br />

serializable:<br />

using System;<br />

using System.Transactions;<br />

namespace Wrox.ProCSharp.Transactions<br />

{<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

var intVal = new Transactional(1);<br />

var student1 = new Transactional(new Student());<br />

student1.Value.FirstName = "Andrew";<br />

student1.Value.LastName = "Wilson";<br />

Console.WriteLine("before the transaction, value: {0}",<br />

intVal.Value);<br />

Console.WriteLine("before the transaction, student: {0}",<br />

student1.Value);<br />

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

{<br />

intVal.Value = 2;<br />

Console.WriteLine("inside transaction, value: {0}", intVal.Value);<br />

student1.Value.FirstName = "Ten";<br />

student1.Value.LastName = "SixtyNine";<br />

}<br />

}<br />

}<br />

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

scope.Complete();<br />

}<br />

Console.WriteLine("outside of transaction, value: {0}",<br />

intVal.Value);<br />

Console.WriteLine("outside of transaction, student: {0}",<br />

student1.Value);<br />

code snippet CustomResource/Program.cs<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!