15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Custom resource Managers ❘ 629<br />

The method SetValue() is very similar to GetValue(); the difference is that it changes the live or<br />

temporary value:<br />

protected virtual T GetValue()<br />

{<br />

if (Transaction.Current == null)<br />

{<br />

return liveValue;<br />

}<br />

else<br />

{<br />

return GetEnlistment().Value;<br />

}<br />

}<br />

protected virtual void SetValue(T value)<br />

{<br />

if (Transaction.Current == null)<br />

{<br />

liveValue = value;<br />

}<br />

else<br />

{<br />

GetEnlistment().Value = value;<br />

}<br />

}<br />

The Commit() <strong>and</strong> Rollback() methods that are implemented in the class Transactional are invoked<br />

from the resource manager. The Commit() method sets the live value from the temporary value received<br />

with the first argument <strong>and</strong> nullifies the variable enlistedTransaction as the transaction is completed.<br />

With the Rollback() method, the transaction is completed as well, but here the temporary value is<br />

ignored, <strong>and</strong> the live value is kept in use:<br />

}<br />

internal void Commit(T value, Transaction tx)<br />

{<br />

liveValue = value;<br />

enlistedTransaction = null;<br />

}<br />

internal void Rollback(Transaction tx)<br />

{<br />

enlistedTransaction = null;<br />

}<br />

Because the resource manager that is used by the class Transactional is used only within the<br />

Transactional class itself, it is implemented as an inner class. With the constructor, the parent variable<br />

is set to have an association with the transactional wrapper class. The temporary value used within the<br />

transaction is copied from the live value. Remember the isolation requirements with transactions:<br />

using System;<br />

using System.Diagnostics;<br />

using System.IO;<br />

using System.Runtime.Serialization.Formatters.Binary;<br />

using System.Transactions;<br />

namespace Wrox.ProCSharp.Transactions<br />

{<br />

public partial class Transactional<br />

{<br />

internal class ResourceManager: IEnlistmentNotification<br />

{<br />

private Transactional parent;<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!