using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Workflow.Runtime;
namespace Securancy.Extensions.Workflow
{
public static class WorkflowExecutive
{
/// <summary>
/// Dynamically executes a workflow during runtime.
/// </summary>
/// <param name="workflowType">typeof<T> where T is the Workflow Type.</param>
/// <param name="namedArgumentValues">Dictionary list (string, object) with the optional parameters.</param>
/// <remarks>
/// The static InvokeWorkflow method allows you to easily execute an existing workflow or activity.
/// It will also rethrow any unhandled errors thrown by a workflow.
/// </remarks>
/// <example>
/// Dictionary<string, object> args = new Dictionary<string, object>();
/// Person customerParam = new Person();
/// customerParam.BirthDate = DateTime.Now.AddYears(-21);
/// args.Add("CustomerInstance", customerParam);
///
/// InvokeWorkflow(typeof(ZeelandNet.Services.BusinessProcesses.ValidateCustomer), args);
/// </example>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes", Justification = "Exception ex = a valid Exception Type.")]
public static void InvokeWorkflow(Type workflowType, Dictionary<string, object> namedArgumentValues)
{
using (WorkflowRuntime workflowRuntime = new WorkflowRuntime())
{
AutoResetEvent waitHandle = new AutoResetEvent(false);
Exception eResult = null;
#region -- Workflow Events --
workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
{
// All is well:
waitHandle.Set();
};
workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
{
// An exception has occured:
if (e.Exception != null) { eResult = new Exception(e.Exception.Message, e.Exception); }
waitHandle.Set();
};
#endregion
// Initialize and start the workflow:
WorkflowInstance workflowInstance = workflowRuntime.CreateWorkflow(workflowType, namedArgumentValues);
workflowInstance.Start();
waitHandle.WaitOne();
#region -- Finalize and cleanup --
// If the WorkflowRuntime threw an error, spit it out:
if (eResult != null) { throw eResult; }
#endregion
}
}
}
}