/// <summary>
        /// Creates a new Workflow Application instance and executes the Current Workflow
        /// </summary>
        private void CmdWorkflowRun(object sender, ExecutedRoutedEventArgs e)
        {
            //get workflow source from designer
            CustomWfDesigner.Instance.Flush();
            MemoryStream workflowStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(CustomWfDesigner.Instance.Text));

            ActivityXamlServicesSettings settings = new ActivityXamlServicesSettings()
            {
                CompileExpressions = true
            };

            DynamicActivity activityExecute = ActivityXamlServices.Load(workflowStream, settings) as DynamicActivity;

            //configure workflow application
            consoleExecutionLog.Text = String.Empty;
            consoleOutput.Text       = String.Empty;
            _executionLog            = new CustomTrackingParticipant();
            _wfApp = new WorkflowApplication(activityExecute);
            _wfApp.Extensions.Add(_executionLog);
            _wfApp.Completed = WfExecutionCompleted;

            //execute
            _wfApp.Run();

            //enable timer for real-time logging
            _timer.Start();
        }
Пример #2
0
        private void LogTracks(int workflowRunId, CustomTrackingParticipant tracker)
        {
            var tracks = MapTracks(tracker.Records, (t) =>
            {
                t.WorkflowRunId = workflowRunId;
                return(t);
            });

            using (WorkflowContext context = new WorkflowContext())
            {
                context.Tracks.AddRange(tracks);
                context.SaveChanges();
            }
        }
Пример #3
0
        public IList<TrackingRecord> StartWorkflow(int id, Dictionary<string, object> wfParams)
        {
            string fileLocation = null;
            int workflowRunId = 0;
            using (var context = new WorkflowContext())
            {
                fileLocation = context.Workflows.First(c => c.Id == id).FileLocation; // Hier kan een NullReferenceException optreden
                var workflowRun = new WorkflowRun()
                {
                    WorkflowId = id,
                    StartTime = DateTime.Now
                };
                context.WorkflowRuns.Add(workflowRun);
                context.SaveChanges();
                workflowRunId = workflowRun.WorkflowRunId;
            }

            var xamlData = ReadXamlFile(fileLocation);

            var tracker = new CustomTrackingParticipant();
            var wf = ActivityXamlServices.Load(new StringReader(xamlData), new ActivityXamlServicesSettings {  CompileExpressions = true });

            AutoResetEvent syncEvent = new AutoResetEvent(false);
            WorkflowApplication wfApp = new WorkflowApplication(wf, wfParams);
            wfApp.Extensions.Add(tracker);
            wfApp.Extensions.Add<TextWriter>(() => new StreamWriter(@"C:/XAML/log.txt"));
            // Handle the desired lifecycle events.
            Exception exception = null;

            wfApp.Completed = (e) => syncEvent.Set();
            wfApp.OnUnhandledException += (WorkflowApplicationUnhandledExceptionEventArgs e) =>
            {
                using (WorkflowContext context = new WorkflowContext())
                {
                    context.Tracks.Add(new Track()
                    {
                        ActivityName = e.UnhandledException.ToString(),
                        EventTime = DateTime.Now.AddHours(-1),
                        State = "Faulted",
                        WorkflowRunId = workflowRunId,
                    });
                    context.SaveChanges();
                }
                LogTracks(workflowRunId, tracker);

                return UnhandledExceptionAction.Terminate;
            };

            // Start the workflow.
            wfApp.Run();
            syncEvent.WaitOne();

            LogTracks(workflowRunId, tracker);

            return tracker.Records;
        }
Пример #4
0
        private void LogTracks(int workflowRunId, CustomTrackingParticipant tracker)
        {
            var tracks = MapTracks(tracker.Records, (t) =>
            {
                t.WorkflowRunId = workflowRunId;
                return t;
            });

            using (WorkflowContext context = new WorkflowContext())
            {
                context.Tracks.AddRange(tracks);
                context.SaveChanges();
            }
        }
Пример #5
0
        public JObject CreateWorkFlow(string libID)   //起草者创建流程,并保存到微软持续化数据库中
        {
            AutoResetEvent      syncEvent     = new AutoResetEvent(false);
            string              currentUserId = User.Identity.GetUserId();
            ApplicationUser     user          = db.Users.Include(i => i.Roles).FirstOrDefault(i => i.Id == currentUserId); //获取当前用户username
            WorkFlowInParameter WfInData      = new WorkFlowInParameter();

            WfInData.drafter = user.UserName;
            Dictionary <string, object> inputs = new Dictionary <string, object>();

            inputs.Add("WfIn", WfInData);
            //var act = CreateActivityFrom(Server.MapPath("~") + "\\WorkFlow\\ItService.xaml");
            WorkflowApplication wfApp = new WorkflowApplication(new ItService(), inputs)
            {
                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)
                {
                    syncEvent.Set();
                },
                OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
                {
                    return(UnhandledExceptionAction.Terminate);
                },
                Idle = delegate(WorkflowApplicationIdleEventArgs e)
                {
                }
            };
            var StateTracker = new StateMachineStateTracker(wfApp.WorkflowDefinition); //当前状态追踪

            wfApp.Extensions.Add(StateTracker);
            wfApp.Extensions.Add(new StateTrackerPersistenceProvider(StateTracker));
            var cu = new CustomTrackingParticipant();         //获取Activity内部变量

            wfApp.Extensions.Add(cu);                         //获取Activity内部变量需要的追踪器
            Guid instanceId = wfApp.Id;

            //var trackerInstance = StateMachineStateTracker.LoadInstance(id, wfApp.WorkflowDefinition, ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            wfApp.Run();
            syncEvent.WaitOne();
            //string CurrentUser = cu.Outputs["CurrentUser"].ToString();
            //var Pt = StateTracker.PossibleTransitions;
            //var CurrentState = StateTracker.CurrentState;

            //BookmarkResumptionResult result = wfApp.ResumeBookmark("Hello123", "ddd");
            var Pt = GetPossibleTransitions(libID, true, 1);

            string[] strs = Pt.Split(',');

            JObject json = new JObject(
                new JProperty("instanceId", instanceId),
                new JProperty("rows",
                              new JArray(
                                  from r in strs
                                  select new JObject(
                                      new JProperty("ID", r.ToString()),
                                      new JProperty("Name", r.ToString())))));

            return(json);
        }
Пример #6
0
        public ActionResult ToNextState(ItServiceItem isi, Guid instanceId, string NextLink, string libid, string Opinion)  //审批者到下一环节,思路:保存当前流程的数据,恢复bookmark到下一环节,并保存下一环节流程信息
        {
            #region 判断是不是当前处理人
            WorkFlowItem    cwfi          = bdb.WorkFlowItems.Where(i => i.WfInstanceId == instanceId).FirstOrDefault();
            string          currentUserId = User.Identity.GetUserId();
            ApplicationUser user          = db.Users.Include(i => i.Roles).FirstOrDefault(i => i.Id == currentUserId);
            if (cwfi.WfCurrentUser.ToString().Trim() != user.UserName.ToString().Trim())
            {
                var json = new
                {
                    errorMsg = "你不是当前处理人"
                };

                return(Json(json, "text/html", JsonRequestBehavior.AllowGet));
            }
            #endregion
            string[]            strs       = NextLink.Trim().Split('(');
            AutoResetEvent      syncEvent  = new AutoResetEvent(false);
            int                 isComplete = 0;
            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)
                {
                    isComplete = 1;
                    syncEvent.Set();
                },
                Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
                {
                },
                Unloaded = delegate(WorkflowApplicationEventArgs e)
                {
                    syncEvent.Set();
                },
                OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
                {
                    return(UnhandledExceptionAction.Terminate);
                },
                Idle = delegate(WorkflowApplicationIdleEventArgs e)
                {
                }
            };
            var StateTracker = new StateMachineStateTracker(wfApp.WorkflowDefinition); //当前状态追踪
            wfApp.Extensions.Add(StateTracker);
            wfApp.Extensions.Add(new StateTrackerPersistenceProvider(StateTracker));
            var cu = new CustomTrackingParticipant();         //获取Activity内部变量
            wfApp.Extensions.Add(cu);                         //获取Activity内部变量需要的追踪器
            //Guid instanceId = wfApp.Id;
            var trackerInstance = StateMachineStateTracker.LoadInstance(instanceId, wfApp.WorkflowDefinition, ConfigurationManager.ConnectionStrings["ApacheConnection"].ConnectionString);
            wfApp.Load(instanceId);
            BookmarkResumptionResult result = wfApp.ResumeBookmark(trackerInstance.CurrentState, strs[0]);
            //BookmarkResumptionResult result = wfApp.ResumeBookmark(trackerInstance.CurrentState, NextLink.Trim());   //恢复当前状态,并进入下一个bookmark,注意使用Trim,开始没使用,NextLInk无法取到,调试了大半夜
            syncEvent.WaitOne();

            string CurrentUser;
            string OpinionField = "";
            string CurrentState;
            string completeStr = "";

            if (isComplete == 0)
            {
                if (strs.Count() == 1)
                {
                    CurrentUser = cu.Outputs["CurrentUser"].ToString();
                }
                else
                {
                    CurrentUser = db.LibraryApprovers.ToList().First(p => (p.LibID == libid) && (p.ApproverName == strs[1].Replace(")", ""))).Approver;
                }
                OpinionField = cu.Outputs["OpinionField"].ToString();
                CurrentState = StateTracker.CurrentState;
            }
            else
            {
                CurrentUser  = "******";
                CurrentState = "已结束";
                completeStr  = "->结束";
            }
            //string currentUserId = User.Identity.GetUserId();
            //ApplicationUser user = db.Users.Include(i => i.Roles).FirstOrDefault(i => i.Id == currentUserId);    //获取当前用户TrueName,为增加流转信息提供数据
            WorkFlowItem  wfi  = bdb.WorkFlowItems.Where(i => i.WfInstanceId == instanceId).FirstOrDefault();   //获取当前流程信息
            ItServiceItem cisi = bdb.ItServiceItems.Where(i => i.ID == isi.ID).FirstOrDefault();                //获取当前业务数据的信息

            //业务数据更新开始
            cisi.Title          = isi.Title;
            cisi.applicant      = isi.applicant;
            cisi.applicant_dept = isi.applicant_dept;
            //cisi.description = isi.description;
            cisi.isitype     = isi.isitype;
            cisi.sub_isitype = isi.sub_isitype;
            cisi.end_isitype = isi.end_isitype;
            cisi.Object      = isi.Object;
            cisi.Topic       = isi.Topic;
            cisi.Purpose     = isi.Purpose;
            cisi.Status      = 1;
            if (NextLink == "驳回")
            {
                cisi.Status = 3;
            }
            if (isComplete == 1)
            {
                cisi.isiCompleteDate = DateTime.Now;
                if (NextLink == "撤销")
                {
                    cisi.Status = 4;
                }
                else
                {
                    cisi.Status = 2;
                }
            }

            #region 审批意见更新开始
            if (Opinion != null)
            {
                if (Convert.ToString(Opinion) != "")
                {
                    if (wfi.WfWriteField.Trim() == "FirstExamine")
                    {
                        cisi.FirstExamine = cisi.FirstExamine + "<br>" + Opinion + "     (意见填写人:" + user.TrueName + "    时间:" + DateTime.Now + ")";
                    }
                    if (wfi.WfWriteField.Trim() == "SecondExamine")
                    {
                        cisi.SecondExamine = cisi.SecondExamine + "<br>" + Opinion + "     (意见填写人:" + user.TrueName + "    时间:" + DateTime.Now + ")";
                    }
                    if (wfi.WfWriteField.Trim() == "LastExamine")
                    {
                        cisi.LastExamine = cisi.LastExamine + "<br>" + Opinion + "     (意见填写人:" + user.TrueName + "    时间:" + DateTime.Now + ")";
                    }
                }
            }
            #endregion


            if (wfi != null)
            {
                wfi.WfCurrentUser = CurrentUser;
                wfi.Wfstatus      = CurrentState;
                wfi.WfWriteField  = OpinionField;
                if (isComplete == 1)
                {
                    wfi.WfCompleteDate = DateTime.Now;
                }
                wfi.WfFlowChart = wfi.WfFlowChart + "->" + trackerInstance.CurrentState + "(" + user.TrueName + ")" + completeStr;          //增加流转信息
                try
                {
                    bdb.SaveChanges();
                    var json = new
                    {
                        okMsg = "提交成功"
                    };

                    return(Json(json, "text/html", JsonRequestBehavior.AllowGet));
                }
                catch (Exception e)
                {
                    var json = new
                    {
                        errorMsg = "提交失败"
                    };

                    return(Json(json, "text/html", JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                var json = new
                {
                    errorMsg = "流程不存在"
                };

                return(Json(json, "text/html", JsonRequestBehavior.AllowGet));
            }
        }
Пример #7
0
        public ActionResult DrafterToNextState(ItServiceItem isi, Guid instanceId, string NextLink, string libid)  //起草者到下一环节
        {
            string[] strs = NextLink.Trim().Split('(');

            AutoResetEvent syncEvent = new AutoResetEvent(false);

            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)
                {
                    syncEvent.Set();
                },
                OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
                {
                    return(UnhandledExceptionAction.Terminate);
                },
                Idle = delegate(WorkflowApplicationIdleEventArgs e)
                {
                }
            };
            var StateTracker = new StateMachineStateTracker(wfApp.WorkflowDefinition); //当前状态追踪

            wfApp.Extensions.Add(StateTracker);
            wfApp.Extensions.Add(new StateTrackerPersistenceProvider(StateTracker));
            var cu = new CustomTrackingParticipant();         //获取Activity内部变量

            wfApp.Extensions.Add(cu);                         //获取Activity内部变量需要的追踪器
            //Guid instanceId = wfApp.Id;
            var trackerInstance = StateMachineStateTracker.LoadInstance(instanceId, wfApp.WorkflowDefinition, ConfigurationManager.ConnectionStrings["ApacheConnection"].ConnectionString);

            wfApp.Load(instanceId);
            //BookmarkResumptionResult result = wfApp.ResumeBookmark(trackerInstance.CurrentState, NextLink.Trim());
            BookmarkResumptionResult result = wfApp.ResumeBookmark(trackerInstance.CurrentState, strs[0]);

            syncEvent.WaitOne();
            //string CurrentUser = cu.Outputs["CurrentUser"].ToString();
            string CurrentUser = db.LibraryApprovers.ToList().First(p => (p.LibID == libid) && (p.ApproverName == strs[1].Replace(")", ""))).Approver;
            //string CurrentRole = cu.Outputs["CurrentRole"].ToString();
            string OpinionField = cu.Outputs["OpinionField"].ToString();
            string Drafter      = cu.Outputs["Drafter"].ToString();
            var    CurrentState = StateTracker.CurrentState;
            //var Pt = StateTracker.PossibleTransitions;
            ApplicationUser user = db.Users.Include(i => i.Roles).FirstOrDefault(i => i.UserName == Drafter);    //获取当前用户username

            isi.drafter       = Drafter;
            isi.isiCreateDate = DateTime.Now;
            isi.Status        = 1;
            bdb.ItServiceItems.Add(isi);      //添加业务数据
            try
            {
                bdb.SaveChanges();
            }
            catch
            {
                var json = new
                {
                    errorMsg = "添加业务数据出错"
                };

                return(Json(json, "text/html", JsonRequestBehavior.AllowGet));
            }
            WorkFlowItem wf = new WorkFlowItem();

            wf.WfInstanceId   = instanceId;
            wf.WfType         = "专病库IT服务申请";
            wf.WfCurrentUser  = CurrentUser;
            wf.WfDrafter      = Drafter;
            wf.WfWriteField   = OpinionField;
            wf.Wfstatus       = CurrentState;
            wf.WfBussinessUrl = "/ItService/OpenWorkFlow?id=" + instanceId;
            wf.WfCreateDate   = DateTime.Now;
            wf.WfBusinessId   = isi.ID; //添加业务数据关联
            wf.WfFlowChart    = trackerInstance.CurrentState + "(" + user.TrueName + ")";
            bdb.WorkFlowItems.Add(wf);
            bdb.SaveChanges();
            try
            {
                bdb.SaveChanges();
                var json = new
                {
                    okMsg = "流程保存成功"
                };

                return(Json(json, "text/html", JsonRequestBehavior.AllowGet));
            }
            catch
            {
                var json = new
                {
                    errorMsg = "流程保存出错"
                };

                return(Json(json, "text/html", JsonRequestBehavior.AllowGet));
            }
        }
Пример #8
0
        public IList <TrackingRecord> StartWorkflow(int id, Dictionary <string, object> wfParams)
        {
            string fileLocation  = null;
            int    workflowRunId = 0;

            using (var context = new WorkflowContext())
            {
                fileLocation = context.Workflows.First(c => c.Id == id).FileLocation; // Hier kan een NullReferenceException optreden
                var workflowRun = new WorkflowRun()
                {
                    WorkflowId = id,
                    StartTime  = DateTime.Now
                };
                context.WorkflowRuns.Add(workflowRun);
                context.SaveChanges();
                workflowRunId = workflowRun.WorkflowRunId;
            }

            var xamlData = ReadXamlFile(fileLocation);

            var tracker = new CustomTrackingParticipant();
            var wf      = ActivityXamlServices.Load(new StringReader(xamlData), new ActivityXamlServicesSettings {
                CompileExpressions = true
            });

            AutoResetEvent      syncEvent = new AutoResetEvent(false);
            WorkflowApplication wfApp     = new WorkflowApplication(wf, wfParams);

            wfApp.Extensions.Add(tracker);
            wfApp.Extensions.Add <TextWriter>(() => new StreamWriter(@"C:/XAML/log.txt"));
            // Handle the desired lifecycle events.
            Exception exception = null;

            wfApp.Completed             = (e) => syncEvent.Set();
            wfApp.OnUnhandledException += (WorkflowApplicationUnhandledExceptionEventArgs e) =>
            {
                using (WorkflowContext context = new WorkflowContext())
                {
                    context.Tracks.Add(new Track()
                    {
                        ActivityName  = e.UnhandledException.ToString(),
                        EventTime     = DateTime.Now.AddHours(-1),
                        State         = "Faulted",
                        WorkflowRunId = workflowRunId,
                    });
                    context.SaveChanges();
                }
                LogTracks(workflowRunId, tracker);

                return(UnhandledExceptionAction.Terminate);
            };


            // Start the workflow.
            wfApp.Run();
            syncEvent.WaitOne();

            LogTracks(workflowRunId, tracker);

            return(tracker.Records);
        }