Transactions can be used in a wide variety of implementations in order to resolve synchronization issues and define business logic units. Transactions can be created anywhere in the code, and started due to any event or service call. The following implementations are examples of how to solve a number of design problems using transactions.
This pattern can be used for monitor or error handling, which requires constantly monitoring for some events and performing a specific action on these events.
The following example shows how to catch every popup window opened from an application and close it, by clicking the Cancel button. The transaction should be initialized in the appropriate scope (e.g., as a member). If returning a result is required, the same transaction could be reused by calling Result after getting a value back.
class ContinuousTransaction : Transaction<bool>
{
private Process _std;
private StandardControls _stdWnd;
public ContinuousTransaction(Service srv) : base(srv, TimeSpan.FromSeconds(5))
{
Service.WindowOpened += this.WindowOpened;
}
private void WindowOpened(object sender, EventArgs e)
{
if (sender is StandardControls)
{
_stdWnd = sender as StandardControls;
_stdWnd.WindowOpened += this.openWnd_WindowOpened;
|
_stdWnd.FileMenuItem.OpenMenuItem.Pick();
}
}
|
(sender as StandardControls.OpenWindow).CancelButton.Click();
SetResult(true);
}
}
…………………………………………………………………………
for(int i = 0; i < itr; ++i)
{
_std = NunitProjectApp.Service.StartStandardApp();
bRes = bRes && Result;
}
|
|
Another transaction pattern is the nested transaction. This pattern should be divided into a number of simple transactions. Advantages of this method are that it is easy to maintain and easy to understand. In addition, the transactions code can be reused in different complex transactions.
class NestedTransaction : Transaction<string>
{
public NestedTransaction(Service srv) : base(srv)
{
}
public string StartTransaction()
{
string retVal = "Failed";
try
{
int num = new StdTransaction((Service)this.Service).StartTransaction();
string name = new IETransaction((Service)this.Service, num).StartTransaction();
string ret = new NotepadTransaction((Service)this.Service, name + num).StartTransaction();
if (ret == name + num)
retVal = "Succeed";
}
catch (Exception ex)
{
retVal += ": " + ex;
}
return retVal;
}
|
|