public static void Run() { WorkflowApplication app1 = new WorkflowApplication("app1"); _applications.Add("app1", app1); app1.StartRuntime(); Dictionary<string, object> wfArguments = new Dictionary<string, object>(); wfArguments.Add("InputString", "1"); _applications["app1"].StartWorkflow(typeof(Workflow1), wfArguments); _applications["app1"].StartWorkflow(typeof(Workflow1), wfArguments); _applications["app1"].StartWorkflow(typeof(Workflow1), wfArguments); WorkflowApplication app2 = new WorkflowApplication("app2"); _applications.Add("app2", app2); app2.StartRuntime(); _applications["app1"].StartWorkflow(typeof(Workflow1), wfArguments); _applications["app1"].StartWorkflow(typeof(Workflow1), wfArguments); Thread.Sleep(15000); app1.Dispose(); app2.Dispose(); Console.ReadLine(); }
private void Start(Func <WorkflowIdentity, Activity> workflowMap, WorkflowIdentity workflowIdentity, IDictionary <string, object> inputs) { // >>>> START A WORKFLOW <<<< Activity workflow = workflowMap(workflowIdentity); WorkflowApplication wfApp = new WorkflowApplication(workflow, inputs, workflowIdentity); // Configure the instance store, extensions, and // workflow lifecycle handlers. ConfigureWorkflowApplication(wfApp); // Start the workflow. wfApp.Run(); }
private static Boolean IsBookmarkValid( WorkflowApplication wfApp, String bookmarkName) { Boolean result = false; var bookmarks = wfApp.GetBookmarks(); if (bookmarks != null) { result = (from b in bookmarks where b.BookmarkName == bookmarkName select b).Any(); } return(result); }
void OnEndResumeBookmark(IAsyncResult ar) { object[] asyncState = ar.AsyncState as object[]; WorkflowApplication instance = asyncState[0] as WorkflowApplication; string bookmarkName = asyncState[1] as string; BookmarkResumptionResult result = instance.EndResumeBookmark(ar); if (result != BookmarkResumptionResult.Success) { //it is possible the bookmark has been removed by some other event in the workflow //but that event will update the host - no need to do it here this.hostView.OutputWriter.WriteLine("Could not resume bookmark: {0} on instance {1}", bookmarkName, instance.Id); } }
static void Main(string[] args) { WorkflowApplication wfApp = CreateWorkflowApplication(); var workflowInstanceId = wfApp.Id; wfApp.Run(); string bookmarkName = workflowInstanceId.ToString(); wfApp.Unload(); _unloadedEvent.WaitOne(); /* create */ wfApp = CreateWorkflowApplication(); wfApp.Load(workflowInstanceId); var result = wfApp.ResumeBookmark(bookmarkName, null); // <- this hits the BookmarkActivity while **IT SHOULD'NT** }
public void RespondToRequest(ReservationResponse response) { Guid id = response.RequestID; WorkflowApplication i = _outgoingRequests[id]; try { i.ResumeBookmark("GetResponse", response); } catch (Exception e2) { AddEvent(e2.Message); } }
public static void VerifyWFApplicationEventArgs <T>(WorkflowApplication workflowApplication, WorkflowApplicationEventArgs eventArgs, int expectedExtensionsCount) where T : class { if (eventArgs.InstanceId != workflowApplication.Id) { throw new Exception("Expected instance ID is: " + workflowApplication.Id + " Actual is: " + eventArgs.InstanceId); } int actualCount = eventArgs.GetInstanceExtensions <T>().Count <T>(); if (actualCount != expectedExtensionsCount) { throw new Exception("Expected number of extensions is: " + expectedExtensionsCount + " Actual is: " + actualCount); } }
public static WorkflowApplication CreateWorkflowApplication() { Activity wf = CreateWorkflow(); WorkflowApplication result = new WorkflowApplication(wf) { InstanceStore = new XmlWorkflowInstanceStore(uid), Unloaded = e => { _unloadedEvent.Set(); }, PersistableIdle = e => PersistableIdleAction.Unload }; return(result); }
public static WorkflowApplication GetWorkflowApplication(AutomationActivity activity) { var workflowApplication = new WorkflowApplication(activity) { Completed = delegate(WorkflowApplicationCompletedEventArgs e) { switch (e.CompletionState) { case ActivityInstanceState.Faulted: //Logger.GetInstance().Log().Error("workflow " + // scriptGuid + // " stopped! Error Message:\n" // + // e.TerminationException. // GetType().FullName + // "\n" // + // e.TerminationException. // Message); //Status = "Terminated"; break; case ActivityInstanceState.Canceled: //Logger.GetInstance().Log().Warn("workflow " + scriptGuid + // " Cancel."); //Status = "Canceled"; break; //Logger.GetInstance().Log().Info("workflow " + scriptGuid + // " Completed."); //Status = "Completed"; } }, Aborted = delegate { //Logger.GetInstance().Log().Error("workflow " + // scriptGuid // + " aborted! Error Message:\n" // + e.Reason.GetType().FullName + "\n" + // e.Reason.Message); //Status = "Aborted"; } }; return(workflowApplication); }
private static void runTerminate() { AutoResetEvent waitForWorkflow = new AutoResetEvent(false); System.Activities.Statements.Sequence seq = new System.Activities.Statements.Sequence() { Activities = { new System.Activities.Statements.TerminateWorkflow { Exception = new InArgument <Exception>(context => new TAC.ApplicationException()), Reason = new InArgument <string>("just because"), }, new System.Activities.Statements.WriteLine() { Text = "Hello" }, } }; try { WorkflowApplication instance = new WorkflowApplication(seq) { Completed = delegate(WorkflowApplicationCompletedEventArgs args) { Console.WriteLine("Completed workflow status: " + args.CompletionState); if (args.CompletionState == ActivityInstanceState.Faulted) { Console.WriteLine("Termination Inner exception: " + args.TerminationException.InnerException.GetType()); Console.WriteLine("Termination exception Reason is: " + args.TerminationException.Message); Console.WriteLine("Termination exception: " + args.TerminationException); } waitForWorkflow.Set(); } }; Console.WriteLine("Starting"); instance.Run(); waitForWorkflow.WaitOne(); // Complete } catch (Exception e) { Console.WriteLine("Exception is here!"); Console.WriteLine("Type = {0} , Message = {1} , RealException is: {2}", e.GetType(), e.Message, e.InnerException.GetType()); } Console.ReadLine(); }
public void ResumeWorkFlow(BusinessObject.DtoModels.Game game) { Exception exception = new Exception(); Guid workflowInstanceID = game.InstanceId; SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(databaseConnection); store.InstanceLockedExceptionAction = InstanceLockedExceptionAction.BasicRetry; store.HostLockRenewalPeriod = TimeSpan.FromSeconds(2); InstanceHandle instanceHandle = store.CreateInstanceHandle(); CreateWorkflowOwnerCommand createOwnerCmd = new CreateWorkflowOwnerCommand(); InstanceView view = store.Execute(instanceHandle, createOwnerCmd, TimeSpan.FromSeconds(10)); store.DefaultInstanceOwner = view.InstanceOwner; WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(workflowInstanceID, store); AutoResetEvent syncEvent = new AutoResetEvent(false); WorkflowApplication wfApplication = new WorkflowApplication(new FlowchartNumberGuessWorkflow(), instance.DefinitionIdentity); wfApplication.PersistableIdle = (e) => PersistableIdleAction.Unload; wfApplication.Unloaded = (e) => { syncEvent.Set(); }; wfApplication.OnUnhandledException = (e) => { exception = e.UnhandledException; syncEvent.Set(); return(UnhandledExceptionAction.Cancel); }; wfApplication.Load(instance); BookmarkResumptionResult result = wfApplication.ResumeBookmark("Decision", game); syncEvent.WaitOne(); if (exception.Message != string.Empty && exception.StackTrace != null) { throw exception; } DeleteWorkflowOwnerCommand deleteOwnerCmd = new DeleteWorkflowOwnerCommand(); store.Execute(instanceHandle, deleteOwnerCmd, TimeSpan.FromSeconds(10)); }
private static void PauseAndResumeNotCorrect() { Variable <string> name = new Variable <string>(); Activity wf = new Sequence { Variables = { name }, Activities = { new WriteLine { Text = "Hello there!" }, new WaitForData <string> { BookmarkName = "WaitForUserInputData", Result = new OutArgument <string>(name) }, new WriteLine { Text = new InArgument <string>((env) => ("Hello, " + name.Get(env))) } } }; WorkflowApplication wfApp = new WorkflowApplication(wf); wfApp.Completed += (wce) => { var response = "blah"; //(string)wce.Outputs["Result"]; Console.Write($"Workflow completed, Result is {response}"); }; wfApp.Idle += (wie) => { Console.Write("Workflow idle!"); }; wfApp.Run(); Console.WriteLine("What's your name?"); var input = Console.ReadLine(); var result = wfApp.ResumeBookmark("WaitForUserInputData", input); Console.WriteLine($"Bookmark resume result: {result}, output data: {name.ToString()}"); }
private void AbortWorkers() { foreach (JobSlice jobSlice in job.JobSlices) { try { if (jobSlice.WorkflowInstanceId != Guid.Empty) { WorkflowApplication wfApp = new WorkflowApplication(new Worker()); wfApp.Load(jobSlice.WorkflowInstanceId); wfApp.Cancel(); } } catch { } } }
public void Run() { var stream = new MemoryStream(Encoding.ASCII.GetBytes(_workflowDesigner.Text)); var workflow = ActivityXamlServices.Load(stream); var wa = new WorkflowApplication(workflow); var txtFileTrackingParticipant = new TxtFileTrackingParticipant { TrackingProfile = Etw() }; wa.Extensions.Add(txtFileTrackingParticipant); wa.Completed = Completed; wa.OnUnhandledException = UnhandledException; wa.Run(); }
public void RequestBook(ReservationRequest request) { // Setup a dictionary object for passing parameters Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters.Add("request", request); parameters.Add("Writer", new ListBoxTextWriter(lstEvents)); WorkflowApplication i = new WorkflowApplication(new ProcessRequest(), parameters); request.InstanceID = i.Id; _incomingRequests.Add(i.Id, i); i.Run(); }
private static void InitWF(WorkflowApplication wfa) { string cnnstr = System.Configuration.ConfigurationManager.ConnectionStrings["master"].ConnectionString; var sqlstore = new System.Activities.DurableInstancing.SqlWorkflowInstanceStore(cnnstr); var handler = sqlstore.CreateInstanceHandle(); var view = sqlstore.Execute(handler, new System.Activities.DurableInstancing.CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30)); sqlstore.DefaultInstanceOwner = view.InstanceOwner; handler.Free(); wfa.InstanceStore = sqlstore; wfa.Aborted = AbortedHandler; wfa.OnUnhandledException = OnUnhandledExceptionHandler; wfa.Completed = CompletedHandler; wfa.PersistableIdle = PersistableIdleHandler; }
public WorkflowApplicationInstance GetInstance(Guid workflowInstanceID) { SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(databaseConnection); store.InstanceLockedExceptionAction = InstanceLockedExceptionAction.BasicRetry; store.HostLockRenewalPeriod = TimeSpan.FromSeconds(2); InstanceHandle instanceHandle = store.CreateInstanceHandle(); CreateWorkflowOwnerCommand createOwnerCmd = new CreateWorkflowOwnerCommand(); InstanceView view = store.Execute(instanceHandle, createOwnerCmd, TimeSpan.FromSeconds(10)); store.DefaultInstanceOwner = view.InstanceOwner; return(WorkflowApplication.GetInstance(workflowInstanceID, store)); }
// start a workflow instance and configure OOB persistence static WorkflowApplication StartWorkflow(Activity program, AutoResetEvent resetEvent) { // create the application WorkflowApplication application = new WorkflowApplication(program); // configure the instance store (in this case we use the Sql OOB instance store) InstanceStore store = new SqlWorkflowInstanceStore(connectionString); application.InstanceStore = store; application.PersistableIdle = (e) => PersistableIdleAction.Persist; // run the workflow RunWorkflow(application, resetEvent); return(application); }
private void button4_Click(object sender, EventArgs e) { //6. Retrive a workflow in database WorkflowApplication application = new WorkflowApplication(new DemoActivity()); SqlWorkflowInstanceStore sqlWorkflowInstanceStore = new SqlWorkflowInstanceStore(strCon); //Connecting current application instance to database. application.InstanceStore = sqlWorkflowInstanceStore; application.PersistableIdle = arg => { return(PersistableIdleAction.Unload); }; // 7 load the retrived workflow. application.Load(Guid.Parse(this.textBox1.Text)); application.ResumeBookmark("UserFinancial", new object[] { "Website", 100000 }); }
public static void ValidateInstantiationException(TestActivity testActivity, Type exceptionType, string errorString) { Dictionary <string, string> exception = new Dictionary <string, string>(); exception.Add("Message", errorString); ExceptionHelpers.CheckForException( exceptionType, exception, delegate { WorkflowApplication instance = new WorkflowApplication(testActivity.ProductActivity); instance.Extensions.Add(TestRuntime.TraceListenerExtension); instance.Run(); }, true); }
private void btnBeginWF_Click(object sender, EventArgs e) { //WorkflowInvoker.Invoke(new DemoActivity(), new Dictionary<string, object>() { // {"BookmarkName", this.textBookmarkName.Text } //}); workflowApplication = new WorkflowApplication(new DemoActivity(), new Dictionary <string, object>() { { "BookmarkName", this.textBookmarkName.Text } }); workflowApplication.Idle += AfterWorkflowIdle; workflowApplication.Run(); }
/// <summary> /// Construct a workflow application and return to the caller /// </summary> /// <param name="finished"></param> /// <returns></returns> private static WorkflowApplication BuildApplication(EventWaitHandle finished) { // Construct the instance store SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["db"].ConnectionString); store.InstanceCompletionAction = InstanceCompletionAction.DeleteAll; // Now create a workflow app WorkflowApplication app = new WorkflowApplication(BuildWorkflow()); app.Completed = (e) => { finished.Set(); }; app.PersistableIdle = (e) => { return(PersistableIdleAction.Unload); }; app.InstanceStore = store; return(app); }
/// <summary> /// The on unload handler. /// </summary> /// <param name="arg"> /// The arg. /// </param> /// <returns> /// The unload handler result (if provided) /// </returns> private bool OnUnloadHandler(WorkflowApplication arg) { try { if (this.OnUnload != null) { return(this.OnUnload(arg)); } return(true); } finally { this.unloadEvent.Set(); } }
public static WorkflowApplication CreateWorkflowApplication(Activity activity, AutoResetEvent completedOrAbortedEvent) { WorkflowApplication instance = new WorkflowApplication(activity) { Completed = (arg) => { completedOrAbortedEvent.Set(); }, Aborted = (arg) => { completedOrAbortedEvent.Set(); } }; return(instance); }
private static void ConfigWfa(WorkflowApplication wfa) { var cnnstr = ""; //配置工作流持久化的数据库 //创建数据库,执行2个脚本C:\Windows\Microsoft.NET\Framework64\v4.0.30319\SQL\zh-Hans\SqlWorkflowInstanceStoreSchema.sql //C:\Windows\Microsoft.NET\Framework64\v4.0.30319\SQL\zh-Hans\SqlWorkflowInstanceStoreLogic.sql wfa.InstanceStore = new System.Activities.DurableInstancing.SqlWorkflowInstanceStore(cnnstr); wfa.Aborted = AbortedHandler; wfa.Completed = CompletedHandler; wfa.Idle = IdleHandler; wfa.OnUnhandledException = OnUnhandledExceptionHandler; wfa.PersistableIdle = PersistableIdleHandler; wfa.Unloaded = UnloadedHandler; }
private void GetReimbursementVoid(Guid id) { // Initialize Windows Workflow Foundation WorkflowApplication _wfApp = new WorkflowApplication(new ReimbursementRequest()); SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["workflows"].ConnectionString); _wfApp.InstanceStore = store; _wfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs ex) { return(PersistableIdleAction.Persist); }; _wfApp.Run(); _wfApp.Unload(); Session["wfid"] = _wfApp.Id; }
//// This method called on notification workflow completion. //internal static void NotificationWFCompleted(WorkflowApplicationCompletedEventArgs e) { // switch (e.CompletionState) { // // If workflow complated without any error. // case ActivityInstanceState.Closed: // #if DEBUG // Console.WriteLine("Workflow Completed."); // #endif // break; // // If any error occurred during workflow execution, will be handled here. // case ActivityInstanceState.Faulted: // Exception ex = e.TerminationException; // ExceptionHandler.HandleException(ref ex, System.Diagnostics.TraceEventType.Error, "Error occured in Notification Workflow", "PresentPolicy"); // break; // } //} // Start notification workflow with provided input parameters. internal static void StartWorkflow(IDictionary <string, object> inputParam, NotificationWFCompleted handler) { // Initialize the notification workflow instance. NotificationWF notificationWF = new NotificationWF(); // Initialize workflow application instance with notification workflow and // with required input argument dictionary. WorkflowApplication wfApp = new WorkflowApplication(notificationWF, inputParam); wfApp.SynchronizationContext = SynchronizationContext.Current; // Attaching a method with workflow completed event. wfApp.Completed = new Action <WorkflowApplicationCompletedEventArgs>(handler); //// Start the workflow execution asynchronously. wfApp.Run(); }
public TResponse Execute <TRequest, TResponse>(TRequest request) { TResponse respnse = default(TResponse); AutoResetEvent syncEvent = new AutoResetEvent(false); //WorkflowInstanceContext<TRequest, TResponse> instanceContext = new WorkflowInstanceContext<TRequest, TResponse>() WorkflowInstanceContext instanceContext = new WorkflowInstanceContext() { Request = request, Response = default(TResponse) }; Dictionary <string, object> inputs = new Dictionary <string, object>(); //inputs.Add("Request", request); WorkflowApplication wf = new WorkflowApplication(this.workflow, inputs); wf.Extensions.Add <WorkflowInstanceContext>(() => { return(instanceContext); }); wf.Completed = e => { syncEvent.Set(); }; wf.Unloaded = e => { syncEvent.Set(); }; wf.Aborted = e => { syncEvent.Set(); }; wf.Idle = e => { syncEvent.Set(); }; wf.PersistableIdle = e => { return(PersistableIdleAction.None); }; wf.OnUnhandledException = e => { return(UnhandledExceptionAction.Terminate); }; wf.Run(); syncEvent.WaitOne(); TResponse response = default(TResponse); try { response = (TResponse)instanceContext.Response; } catch { } return(response); }
public JObject GetPossiblePath(Guid id, string libID) //审批用户获取下一步可能的路径 { WorkFlowItem cwfi = bdb.WorkFlowItems.Where(i => i.WfInstanceId == id).FirstOrDefault(); ItServiceItem cisi = bdb.ItServiceItems.Where(i => i.ID == cwfi.WfBusinessId).FirstOrDefault(); WorkflowApplication wfApp = new WorkflowApplication(new ItService()) { InstanceStore = CreateInstanceStore(), PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e) { //var ex = e.GetInstanceExtensions<CustomTrackingParticipant>(); // Outputs = ex.First().Outputs.ToString(); return(PersistableIdleAction.Unload); }, Completed = delegate(WorkflowApplicationCompletedEventArgs e) { }, Aborted = delegate(WorkflowApplicationAbortedEventArgs e) { }, Unloaded = delegate(WorkflowApplicationEventArgs e) { }, OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e) { return(UnhandledExceptionAction.Terminate); }, Idle = delegate(WorkflowApplicationIdleEventArgs e) { } }; var trackerInstance = StateMachineStateTracker.LoadInstance(id, wfApp.WorkflowDefinition, ConfigurationManager.ConnectionStrings["ApacheConnection"].ConnectionString); //var Pt = trackerInstance.PossibleTransitions; var Pt = GetPossibleTransitions(libID, false, cisi.Status); //BookmarkResumptionResult result = wfApp.ResumeBookmark("Hello123", "ddd"); string[] strs = Pt.Split(','); JObject json = new JObject( new JProperty("rows", new JArray( from r in strs select new JObject( new JProperty("ID", r.ToString()), new JProperty("Name", r.ToString()))))); return(json); }
private void GetBookMarksOnAbortedWorkflow(bool isDefaultTimeout) { const string traceToWaitMsg = "Continue WaitForTrace1"; Sequence sequence = new Sequence() { Activities = { new WaitForTrace() { DisplayName = "WaitForTrace1", TraceToWait = new InArgument <string>(traceToWaitMsg) }, new ReadLine <string>(bookMarkName_InvalidOperationsOnAbortedWorkflow) { } } }; WorkflowApplication instance = new WorkflowApplication(sequence) { Aborted = OnWorkflowInstanceAborted }; instance.Run(); TestTraceManager.Instance.WaitForTrace(instance.Id, new SynchronizeTrace(WaitForTrace.EnterExecute), 1); instance.Abort(); //Continue WaitForTrace. The instance should get aborted after WaitForTrace1 activity is done TestTraceManager.Instance.AddTrace(instance.Id, new SynchronizeTrace(traceToWaitMsg)); SynchronizeTrace.Trace(instance.Id, traceToWaitMsg); TestTraceManager.Instance.WaitForTrace(instance.Id, new SynchronizeTrace(WorkflowInstanceAbortTests.AbortedHandlerCalled), 1); string message = String.Format(ExceptionStrings.WorkflowApplicationAborted, instance.Id); ExceptionHelpers.CheckForException(typeof(WorkflowApplicationAbortedException), message, delegate { if (isDefaultTimeout) { instance.GetBookmarks(); } else { instance.GetBookmarks(TimeSpan.FromMilliseconds(1)); } }); }
private static void RunUpdateBuildNumberInTestCodeActivityUsingWorkflowApplication(IBuildDetail mockBuildDetail) { // Variables - in Variable <string> buildNumberFormat = new Variable <string>("BuildNumberFormat", "Acme.PetShop-Trunk-Full-{0}"); Variable <int> majorVersion = new Variable <int>("MajorVersion", 1); Variable <int> minorVersion = new Variable <int>("MinorVersion", 0); // Variables - out Variable <string> buildNumber = new Variable <string>("BuildNumber"); Variable <string> versionNumber = new Variable <string>("VersionNumber"); // Activities GetBuildDetail getBuildDetail = new GetBuildDetail(); UpdateBuildNumber updateBuildNumber = new UpdateBuildNumber { BuildNumberFormat = buildNumberFormat, MajorVersion = majorVersion, MinorVersion = minorVersion, BuildNumber = buildNumber, VersionNumber = versionNumber }; // Sequence Sequence sequence = new Sequence(); sequence.Variables.Add(buildNumberFormat); sequence.Variables.Add(majorVersion); sequence.Variables.Add(minorVersion); sequence.Variables.Add(buildNumber); sequence.Variables.Add(versionNumber); sequence.Activities.Add(getBuildDetail); sequence.Activities.Add(updateBuildNumber); // Run WorkflowApplication workflowApplication = new WorkflowApplication(sequence); workflowApplication.Extensions.Add(mockBuildDetail); AutoResetEvent idleEvent = new AutoResetEvent(false); workflowApplication.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { idleEvent.Set(); }; workflowApplication.Run(); idleEvent.WaitOne(); }
//when updatng workflow, esp levels, always chnge d processes currnt level to d last new levl, if approval has gone bynd private int SetupApplication() { try { var setting = WorkflowSettings.Settings; if(setting == null) throw new WorkflowDataError("WorkflowSettings section of the web.config file cannot be found."); var _existing = _applications.Table.Where( x => x.Code.ToLower() == setting.Code.ToLower() || x.Name.ToLower() == setting.ApplicationName.ToLower()).FirstOrDefault(); if (_existing == null) { _existing = new WorkflowApplication { Code = setting.Code, Description = setting.Description, Name = setting.ApplicationName }; _applications.Add(_existing); } return _existing.Id; } catch (Exception ex) { throw new WorkflowDataError("Application with same name exists " + ex.Message); } }