private void QuitGame_Click(object sender, EventArgs e)
        {
            if (WorkflowInstanceId == Guid.Empty)
            {
                MessageBox.Show("Please select a workflow.");
                return;
            }

            WorkflowApplicationInstance instance =
                WorkflowApplication.GetInstance(WorkflowInstanceId, store);

            // Use the persisted WorkflowIdentity to retrieve the correct workflow
            // definition from the dictionary.
            Activity wf = WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity);

            // Associate the WorkflowApplication with the correct definition
            WorkflowApplication wfApp =
                new WorkflowApplication(wf, instance.DefinitionIdentity);

            // Configure the extensions and lifecycle handlers
            ConfigureWorkflowApplication(wfApp);

            // Load the workflow.
            wfApp.Load(instance);

            // Terminate the workflow.
            wfApp.Terminate("User resigns.");
        }
Exemplo n.º 2
0
        /// <summary>
        /// 开始执行调试流程
        /// </summary>
        public void Debug()
        {
            //授权检测
            ViewModelLocator.Instance.SplashScreen.DoAuthorizationCheck();

            Activity workflow = ActivityXamlServices.Load(m_xamlPath);

            var result = ActivityValidationServices.Validate(workflow);

            if (result.Errors.Count == 0)
            {
                Messenger.Default.Send(this, "BeginRun");

                m_wfElementToSourceLocationMap = UpdateSourceLocationMappingInDebuggerService();
                m_activityIdToWfElementMap     = BuildActivityIdToWfElementMap(m_wfElementToSourceLocationMap);

                if (m_app != null)
                {
                    m_app.Terminate("");
                }

                m_app = new WorkflowApplication(workflow);
                m_app.OnUnhandledException = WorkflowApplicationOnUnhandledException;
                m_app.Completed            = WorkflowApplicationExecutionCompleted;

                m_simTracker = generateTracker();
                m_app.Extensions.Add(m_simTracker);
                m_app.Extensions.Add(new LogToOutputWindowTextWriter());

                if (workflow is DynamicActivity)
                {
                    var wr = new WorkflowRuntime();
                    wr.RootActivity = workflow;
                    m_app.Extensions.Add(wr);
                }

                m_app.Run();
            }
            else
            {
                // 工作流校验错误,请检查参数配置
                MessageBox.Show(App.Current.MainWindow, ResxIF.GetString("WorkflowCheckError"), ResxIF.GetString("ErrorText"), MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
            public void Terminate()
            {
                try
                {
                    // signal user termination ;)
                    _executionToken.IsUserCanceled = true;

                    // This was cancel which left the activities resident in the background and caused chaos!
                    _instance.Terminate(new Exception("User Termination"), new TimeSpan(0, 0, 0, 60, 0));
                }
                catch (Exception e)
                {
                    Dev2Logger.Log.Error(e);
                    _instance.Abort();
                }

                ExecutableServiceRepository.Instance.Remove(this);
                AssociatedServices.ForEach(s => s.Terminate());
                Dispose();
            }
Exemplo n.º 4
0
        private static void RunActivity(Activity activity, TestType testType)
        {
            Console.WriteLine("\n{0} {1}", activity.DisplayName, testType);

            AutoResetEvent      waitEvent = new AutoResetEvent(false);
            WorkflowApplication wfApp     = new WorkflowApplication(activity);

            wfApp.Completed = (e) =>
            {
                Console.WriteLine("WorkflowApplication.Completed");
                waitEvent.Set();
            };

            wfApp.Aborted = (e) =>
            {
                Console.WriteLine("WorkflowApplication.Aborted");
                waitEvent.Set();
            };

            wfApp.OnUnhandledException = (e) =>
            {
                Console.WriteLine("WorkflowApplication.OnUnhandledException: {0}",
                                  e.UnhandledException.Message);
                return(UnhandledExceptionAction.Cancel);
            };

            wfApp.Run();

            switch (testType)
            {
            case TestType.Cancel:
                Thread.Sleep(100);
                wfApp.Cancel();
                break;

            case TestType.Abort:
                Thread.Sleep(100);
                wfApp.Abort("Abort was called");
                break;

            case TestType.Terminate:
                Thread.Sleep(100);
                wfApp.Terminate("Terminate was called");
                break;

            default:
                break;
            }

            waitEvent.WaitOne(TimeSpan.FromSeconds(60));
        }
Exemplo n.º 5
0
        /// <summary>
        /// 开始执行运行流程
        /// </summary>
        public void Run()
        {
            //授权检测
            ViewModelLocator.Instance.SplashScreen.DoAuthorizationCheck();

            Activity workflow = ActivityXamlServices.Load(m_xamlPath);

            var result = ActivityValidationServices.Validate(workflow);

            if (result.Errors.Count == 0)
            {
                Messenger.Default.Send(this, "BeginRun");

                if (m_app != null)
                {
                    m_app.Terminate("");
                }

                m_app = new WorkflowApplication(workflow);
                m_app.Extensions.Add(new LogToOutputWindowTextWriter());

                if (workflow is DynamicActivity)
                {
                    var wr = new WorkflowRuntime();
                    wr.RootActivity = workflow;
                    m_app.Extensions.Add(wr);
                }

                m_app.OnUnhandledException = WorkflowApplicationOnUnhandledException;
                m_app.Completed            = WorkflowApplicationExecutionCompleted;
                m_app.Run();
            }
            else
            {
                MessageBox.Show(App.Current.MainWindow, "工作流校验错误,请检查参数配置", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 开始执行运行流程
        /// </summary>
        public void Run()
        {
            HasException = false;

            Activity workflow = ActivityXamlServices.Load(m_xamlPath);

            var result = ActivityValidationServices.Validate(workflow);

            if (result.Errors.Count == 0)
            {
                Logger.Debug(string.Format("开始执行工作流文件 {0} ……", m_xamlPath), logger);
                Messenger.Default.Send(this, "BeginRun");

                if (m_app != null)
                {
                    m_app.Terminate("");
                }

                m_app = new WorkflowApplication(workflow);
                m_app.Extensions.Add(new LogToOutputWindowTextWriter());

                if (workflow is DynamicActivity)
                {
                    var wr = new WorkflowRuntime();
                    wr.RootActivity = workflow;
                    m_app.Extensions.Add(wr);
                }

                m_app.OnUnhandledException = WorkflowApplicationOnUnhandledException;
                m_app.Completed            = WorkflowApplicationExecutionCompleted;
                m_app.Run();
            }
            else
            {
                AutoCloseMessageBoxService.Show(App.Current.MainWindow, "工作流校验错误,请检查参数配置", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Exemplo n.º 7
0
        private void Terminate(Guid workflowInstanceId, Func <WorkflowIdentity, Activity> workflowMap,
                               string terminationMessage, Action <string> writelineListener = null)
        {
            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(workflowInstanceId, _store);

            // Use the persisted WorkflowIdentity to retrieve the correct workflow
            // definition from the dictionary.
            Activity wf = workflowMap(instance.DefinitionIdentity);

            // Associate the WorkflowApplication with the correct definition
            WorkflowApplication wfApp = new WorkflowApplication(wf, instance.DefinitionIdentity);

            // Configure the extensions and lifecycle handlers
            ConfigureWorkflowApplication(wfApp, writelineListener);

            // Load the workflow.
            wfApp.Load(instance);

            // Terminate the workflow.
            wfApp.Terminate(terminationMessage);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Allows the demonstration of various scenarios using
        /// WorkflowApplication
        /// </summary>
        private static void BasicApplicationTest(TestScenario scenario)
        {
            AutoResetEvent waitEvent = new AutoResetEvent(false);

            WorkflowApplication wfApp = new WorkflowApplication(
                new HostingDemoWorkflow(),
                new Dictionary <String, Object>
            {
                { "ArgNumberToEcho", 1001 },
            });

            wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                switch (e.CompletionState)
                {
                case ActivityInstanceState.Closed:
                    Console.WriteLine("Host: {0} Closed - Thread:{1} - {2}",
                                      wfApp.Id,
                                      System.Threading.Thread.CurrentThread.ManagedThreadId,
                                      e.Outputs["Result"]);
                    break;

                case ActivityInstanceState.Canceled:
                    Console.WriteLine("Host: {0} Canceled - Thread:{1}",
                                      wfApp.Id,
                                      System.Threading.Thread.CurrentThread.ManagedThreadId);
                    break;

                case ActivityInstanceState.Executing:
                    Console.WriteLine("Host: {0} Executing - Thread:{1}",
                                      wfApp.Id,
                                      System.Threading.Thread.CurrentThread.ManagedThreadId);
                    break;

                case ActivityInstanceState.Faulted:
                    Console.WriteLine(
                        "Host: {0} Faulted - Thread:{1} - {2}:{3}",
                        wfApp.Id,
                        System.Threading.Thread.CurrentThread.ManagedThreadId,
                        e.TerminationException.GetType(),
                        e.TerminationException.Message);
                    break;

                default:
                    break;
                }
                waitEvent.Set();
            };

            wfApp.OnUnhandledException =
                delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
            {
                Console.WriteLine(
                    "Host: {0} OnUnhandledException - Thread:{1} - {2}",
                    wfApp.Id,
                    System.Threading.Thread.CurrentThread.ManagedThreadId,
                    e.UnhandledException.Message);
                waitEvent.Set();
                return(UnhandledExceptionAction.Cancel);
            };

            wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
            {
                Console.WriteLine("Host: {0} Aborted - Thread:{1} - {2}:{3}",
                                  wfApp.Id,
                                  System.Threading.Thread.CurrentThread.ManagedThreadId,
                                  e.Reason.GetType(), e.Reason.Message);
                waitEvent.Set();
            };

            wfApp.Idle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                Console.WriteLine("Host: {0} Idle - Thread:{1}",
                                  wfApp.Id,
                                  System.Threading.Thread.CurrentThread.ManagedThreadId);
            };

            wfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                Console.WriteLine("Host: {0} PersistableIdle - Thread:{1}",
                                  wfApp.Id,
                                  System.Threading.Thread.CurrentThread.ManagedThreadId);
                return(PersistableIdleAction.Unload);
            };

            wfApp.Unloaded = delegate(WorkflowApplicationEventArgs e)
            {
                Console.WriteLine("Host: {0} Unloaded - Thread:{1}",
                                  wfApp.Id,
                                  System.Threading.Thread.CurrentThread.ManagedThreadId);
            };

            try
            {
                Console.WriteLine("Host: About to run {0} - Thread:{1}",
                                  wfApp.Id,
                                  System.Threading.Thread.CurrentThread.ManagedThreadId);

                //determine the demonstration scenario
                switch (scenario)
                {
                case TestScenario.Normal:
                    wfApp.Run();
                    waitEvent.WaitOne();
                    break;

                //case TestScenario.TimeSpan:
                //    wfApp.Run(TimeSpan.FromSeconds(1));
                //    waitEvent.WaitOne();
                //    break;

                case TestScenario.Cancel:
                    wfApp.Run();
                    //Wait just a bit then cancel the workflow
                    Thread.Sleep(1000);
                    wfApp.Cancel();
                    waitEvent.WaitOne();
                    break;

                case TestScenario.Abort:
                    wfApp.Run();
                    //Wait just a bit then abort the workflow
                    Thread.Sleep(1000);
                    wfApp.Abort("My aborted reason");
                    waitEvent.WaitOne();
                    break;

                case TestScenario.Terminate:
                    wfApp.Run();
                    //Wait just a bit then terminate the workflow
                    Thread.Sleep(1000);
                    wfApp.Terminate("My termination reason");
                    waitEvent.WaitOne();
                    break;

                case TestScenario.BeginRun:
                    wfApp.BeginRun(delegate(IAsyncResult ar)
                    {
                        Console.WriteLine(
                            "Host: {0} BeginRunCallback - Thread:{1}",
                            wfApp.Id,
                            System.Threading.Thread.CurrentThread.ManagedThreadId);
                        ((WorkflowApplication)ar.AsyncState).EndRun(ar);
                    }, wfApp);
                    waitEvent.WaitOne();
                    break;

                default:
                    break;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Host: {0} exception:{1}:{2}",
                                  wfApp.Id, exception.GetType(), exception.Message);
            }
        }
Exemplo n.º 9
0
        public void ResetWorkflow(int workflowID, int workflowInstanceID, int userID, List <string> exchangeParamLists)
        {
            Dictionary <string, object> exchangeParams = new Dictionary <string, object>();
            Dictionary <string, object> workflowParams = new Dictionary <string, object>();

            foreach (string item in exchangeParamLists)
            {
                string[] arg = item.Split('^');
                exchangeParams.Add(arg[0], arg[1]);
            }

            WorkflowApplication      workflowApplication = null;
            SqlWorkflowInstanceStore instanceStore       = null;
            InstanceView             view;

            DynEntity workflowInstance = null;

            workflowInstance = GatewayFactory.Default.Find("WorkflowInstance", workflowInstanceID);
            if (workflowInstance != null)
            {
                string definition = ExecuteScalar("select RuntimeDefinition from Workflow where WorkflowID = " + workflowID);
                //加载并运行工作流
                byte[]   bs       = Encoding.UTF8.GetBytes(definition);
                Activity activity = null;
                using (MemoryStream memoryStream = new MemoryStream(bs))
                {
                    activity = ActivityXamlServices.Load(memoryStream);
                }

                workflowApplication = new WorkflowApplication(activity);

                if (instanceStore == null)
                {
                    string connectionString = GatewayFactory.DefaultConnectionString;
                    instanceStore = new SqlWorkflowInstanceStore(connectionString);
                    view          = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
                    instanceStore.DefaultInstanceOwner = view.InstanceOwner;
                }

                workflowApplication.InstanceStore        = instanceStore;
                workflowApplication.PersistableIdle      = workflowPersistableIdle;
                workflowApplication.Idle                 = workflowIdle;
                workflowApplication.Unloaded             = unload;
                workflowApplication.Aborted              = workflowAborted;
                workflowApplication.Completed            = workflowCompleted;
                workflowApplication.OnUnhandledException = workflowUnhandledException;
                Guid guid = new Guid(workflowInstance["InstanceGUID"].ToString());

                try
                {
                    workflowApplication.Load(guid);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                //当用[TerminateWorkflow]结束流程时,流程正常结束.会调用实例的[completed],但状态为[faulted]
                workflowApplication.Terminate("重启工作流实例!");

                //重新启动工作流实例
                workflowApplication = null;
                //获取新工作流实例ID
                int newWorkflowInstanceID = GetNextID("WorkflowInstance");

                workflowParams.Add("WorkflowInstanceID", newWorkflowInstanceID);
                workflowParams.Add("ExchangeParams", exchangeParams);

                workflowApplication = new WorkflowApplication(activity, workflowParams);
                string objType = "";
                int    objID   = 0;
                string command = "";
                if (exchangeParams.ContainsKey("ObjType"))
                {
                    objType = exchangeParams["ObjType"].ToString();
                }
                if (exchangeParams.ContainsKey("ObjID"))
                {
                    objID = Convert.ToInt32(exchangeParams["ObjID"]);
                }
                if (exchangeParams.ContainsKey("Command"))
                {
                    command = exchangeParams["Command"].ToString();
                }

                //添加工作流实例
                workflowInstance = new DynEntity("WorkflowInstance");
                workflowInstance["WorkflowInstanceID"] = newWorkflowInstanceID;
                workflowInstance["WorkflowID"]         = workflowID;
                workflowInstance["StartTime"]          = DateTime.Now;
                workflowInstance["InstanceGUID"]       = workflowApplication.Id.ToString();
                workflowInstance["ObjType"]            = objType;
                workflowInstance["ObjID"]   = objID;
                workflowInstance["Command"] = command;
                workflowInstance["Actor"]   = userID;
                workflowInstance["State"]   = "已保存";

                //添加启动工作流活动实例节点,便于流程历史查看
                int       workflowActivityInstanceID = GetNextID("WorkflowActivityInstance");
                DynEntity workflowActivityInstance   = new DynEntity("WorkflowActivityInstance");
                workflowActivityInstance["WorkflowActivityInstanceID"]   = workflowActivityInstanceID;
                workflowActivityInstance["WorkflowActivityInstanceName"] = "流程重新启动";
                workflowActivityInstance["WorkflowActivityID"]           = -1;
                workflowActivityInstance["WorkflowInstanceID"]           = newWorkflowInstanceID;
                workflowActivityInstance["StartTime"] = DateTime.Now;
                workflowActivityInstance["EndTime"]   = DateTime.Now;
                workflowActivityInstance["Actor"]     = userID;
                workflowActivityInstance["State"]     = "已执行";
                workflowActivityInstance["ObjType"]   = objType;
                workflowActivityInstance["ObjID"]     = objID;
                workflowActivityInstance["Handler"]   = ExecuteScalar("select TrueName from [User] where UserID = " + userID);

                //后续流程处理
                using (TransactionScope trans = new TransactionScope())
                {
                    GatewayFactory.Default.Save(workflowInstance);
                    GatewayFactory.Default.Save(workflowActivityInstance);

                    //更新状态字段
                    string sqlString = "";
                    if (exchangeParams.ContainsKey("ObjType") && exchangeParams.ContainsKey("ObjID") && exchangeParams.ContainsKey("StateField") && exchangeParams.ContainsKey("StateValue"))
                    {
                        sqlString = "UPDATE [" + objType + "] SET [" + exchangeParams["StateField"] + "] = '" + exchangeParams["StateValue"] + "' WHERE " + exchangeParams["ObjType"] + "ID = " + objID;
                        ExcuteNoneReturnQuery(sqlString);
                    }

                    //执行附加SQL
                    if (exchangeParams.ContainsKey("AdditionalSql"))
                    {
                        ExcuteNoneReturnQuery(exchangeParams["AdditionalSql"].ToString());
                    }
                    //删除原工作流实例待做任务
                    ExcuteNoneReturnQuery("Delete WorkflowToDoList where WorkflowInstanceID = " + workflowInstanceID + " and WorkflowID = " + workflowID);
                    //更新原WorkflowActivityInstance
                    sqlString = "UPDATE [WorkflowActivityInstance] SET [EndTime] = '" + DateTime.Now + "', [Actor] = " + userID + ", [State] = '已取消' WHERE WorkflowInstanceID = " + workflowInstanceID;
                    ExcuteNoneReturnQuery(sqlString);

                    workflowApplication.InstanceStore        = instanceStore;
                    workflowApplication.PersistableIdle      = workflowPersistableIdle;
                    workflowApplication.Idle                 = workflowIdle;
                    workflowApplication.Unloaded             = unload;
                    workflowApplication.Aborted              = workflowAborted;
                    workflowApplication.Completed            = workflowCompleted;
                    workflowApplication.OnUnhandledException = workflowUnhandledException;
                    workflowApplication.Run();
                    trans.Complete();
                }
            }
            else
            {
                throw new ApplicationException("数据库中工作流实例不存在,请检查!");
            }
        }
Exemplo n.º 10
0
        public void TerminateWorkflow(int workflowID, int workflowInstanceID, int userID, List <string> exchangeParamLists)
        {
            Dictionary <string, object> exchangeParams = new Dictionary <string, object>();

            foreach (string item in exchangeParamLists)
            {
                string[] arg = item.Split('^');
                exchangeParams.Add(arg[0], arg[1]);
            }

            WorkflowApplication      workflowApplication = null;
            SqlWorkflowInstanceStore instanceStore       = null;
            InstanceView             view;

            DynEntity workflowInstance = null;

            workflowInstance = GatewayFactory.Default.Find("WorkflowInstance", workflowInstanceID);
            if (workflowInstance != null)
            {
                string definition = ExecuteScalar("select RuntimeDefinition from Workflow where WorkflowID = " + workflowID);
                //加载并运行工作流
                byte[]   bs       = Encoding.UTF8.GetBytes(definition);
                Activity activity = null;
                using (MemoryStream memoryStream = new MemoryStream(bs))
                {
                    activity = ActivityXamlServices.Load(memoryStream);
                }

                workflowApplication = new WorkflowApplication(activity);

                if (instanceStore == null)
                {
                    string connectionString = GatewayFactory.DefaultConnectionString;
                    instanceStore = new SqlWorkflowInstanceStore(connectionString);
                    view          = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
                    instanceStore.DefaultInstanceOwner = view.InstanceOwner;
                }

                workflowApplication.InstanceStore        = instanceStore;
                workflowApplication.PersistableIdle      = workflowPersistableIdle;
                workflowApplication.Idle                 = workflowIdle;
                workflowApplication.Unloaded             = unload;
                workflowApplication.Aborted              = workflowAborted;
                workflowApplication.Completed            = workflowCompleted;
                workflowApplication.OnUnhandledException = workflowUnhandledException;
                Guid guid = new Guid(workflowInstance["InstanceGUID"].ToString());

                try
                {
                    workflowApplication.Load(guid);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                workflowApplication.Terminate("终止工作流实例!");

                //后续流程处理
                using (TransactionScope trans = new TransactionScope())
                {
                    //删除待做任务
                    ExcuteNoneReturnQuery("Delete WorkflowToDoList where WorkflowInstanceID = " + workflowInstanceID + " and WorkflowID = " + workflowID);
                    //更新WorkflowActivityInstance
                    string sqlString = "UPDATE [WorkflowActivityInstance] SET [EndTime] = '" + DateTime.Now + "', [Actor] = " + userID + ", [State] = '已取消' WHERE WorkflowInstanceID = " + workflowInstanceID;
                    ExcuteNoneReturnQuery(sqlString);

                    //更新状态字段
                    if (exchangeParams.ContainsKey("ObjType") && exchangeParams.ContainsKey("ObjID") && exchangeParams.ContainsKey("StateField") && exchangeParams.ContainsKey("StateValue"))
                    {
                        sqlString = "UPDATE [" + exchangeParams["ObjType"] + "] SET [" + exchangeParams["StateField"] + "] = '" + exchangeParams["StateValue"] + "' WHERE " + exchangeParams["ObjType"] + "ID = " + exchangeParams["ObjID"];
                        ExcuteNoneReturnQuery(sqlString);
                    }

                    //执行附加SQL
                    if (exchangeParams.ContainsKey("AdditionalSql"))
                    {
                        ExcuteNoneReturnQuery(exchangeParams["AdditionalSql"].ToString());
                    }

                    trans.Complete();
                }
            }
            else
            {
                throw new ApplicationException("数据库中工作流实例不存在,请检查!");
            }
        }