コード例 #1
0
ファイル: IgrssCommon.cs プロジェクト: UrviGandhi/IGRSS
    public static Guid StartWorkflow()
    {
        // Get a reference to the System.Type for the OrderWorkflows.Workflow1
        Type workflowType = typeof(IgrssWorkflowLibrary.ValuationProcess);

        if (workflowType == null)
            return Guid.Empty;

        WorkflowInstance instance = runtime.CreateWorkflow(workflowType);

        StateMachineWorkflowInstance stateMachineInstance = new StateMachineWorkflowInstance(runtime, instance.InstanceId);

        instance.Start();
        // Add the StateMachineInstance object for our Workflow to our dictionary
        stateMachineInstances.Add(instance.InstanceId.ToString(), stateMachineInstance);
        lastWf = instance.InstanceId;

        // Return the WorkflowInstanceId
        return lastWf;
    }
コード例 #2
0
        public void UpgradeWorkflow(WorkflowRuntime runtime, Guid instanceId)
        {
            WorkflowInstance workflowInstance = runtime.GetWorkflow(instanceId);

            var definition = workflowInstance.GetWorkflowDefinition();
            if (!OldAssemblyNames.Contains(definition.GetType().Assembly.FullName))
                return;

            lock (GetLockForWorkflow(instanceId))
            {

                workflowInstance.Unload();

                var are = new AutoResetEvent(false);

                var parameters = new Dictionary<string, object>();

                //Получаем перзистанс и извлекаем состояние
                var persistance = runtime.GetService<NotTerminatingSqlWorkflowPersistenceService>();

                persistance.OnArgsAllowed +=
                    delegate(object sender, NotTerminatingSqlWorkflowPersistenceService.WorkflowSavedParametersArgs e)
                    {
                        if (e.InstanceId == instanceId)
                        {
                            parameters = e.Parameters;
                            are.Set();
                        }
                    };

                workflowInstance = runtime.GetWorkflow(instanceId);

                definition = workflowInstance.GetWorkflowDefinition();
                if (!OldAssemblyNames.Contains(definition.GetType().Assembly.FullName))
                    //Если версия изменилась то дальнейшие манипуляции не нужны
                    return;
                
                are.WaitOne(10000);

                workflowInstance.Unload();

                using (var context = this.CreateContext())
                {
                    context.DeleteWorkflowInPesistenceStore(instanceId);
                    context.SubmitChanges();
                }
                var workflowState = WorkflowStateService.GetWorkflowState(instanceId);

                parameters.Add(StateMachineWithSimpleContainer.DontWriteToWorkflowHistoryPersistenceKey, true);

                using (var sync = new WorkflowSync(runtime, instanceId))
                {
                    if (!CreateWorkflowIfNotExists(runtime, instanceId, workflowState.Type, parameters))
                        //Это ожидание создания воркфлоу
                    {
                        sync.WaitHandle.WaitOne(600000);
                    }

                }

                var wfinstance = new StateMachineWorkflowInstance(runtime, instanceId);
                using (var sync = new WorkflowSync(runtime, instanceId))
                    //Это ожидание завершения установки состояния воркфлоу
                {
                    wfinstance.SetState(workflowState.WorkflowStateName);
                    sync.WaitHandle.WaitOne(600000);
                }

                var args = new SetWorkflowInternalParametersEventArgs(instanceId,
                                                                      new Dictionary<string, object>()
                                                                          {
                                                                              {
                                                                                  StateMachineWithSimpleContainer.
                                                                                  DontWriteToWorkflowHistoryPersistenceKey
                                                                                  ,
                                                                                  false
                                                                                  }
                                                                          });
                SetInternalParameters(null, args);
            }

        }
コード例 #3
0
ファイル: SMTWorkFlowManage.cs プロジェクト: JuRogn/OA
        /// <summary>
        /// 激发事件到一下状态,并获取状态代码
        /// </summary>
        /// <param name="WfRuntime"></param>
        /// <param name="instance"></param>
        /// <param name="CurrentStateName"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static string GetNextStateByEvent(WorkflowRuntime WfRuntime, WorkflowInstance instance, string CurrentStateName, string xml)
        {
            try
            {
                if (!WfRuntime.IsStarted)
                {
                    WfRuntime.StartRuntime();
                }
                WfRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                {
                    instance = null;

                };
                StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(WfRuntime, instance.InstanceId);

                ManualWorkflowSchedulerService scheduleService = WfRuntime.GetService(typeof(ManualWorkflowSchedulerService)) as ManualWorkflowSchedulerService;
                scheduleService.RunWorkflow(workflowinstance.InstanceId);
                workflowinstance.SetState(CurrentStateName);

                FlowDataType.FlowData FlowData = new FlowDataType.FlowData();
                FlowData.xml = xml;

                scheduleService.RunWorkflow(instance.InstanceId);
               WfRuntime.GetService<FlowEvent>().OnDoFlow(instance.InstanceId, FlowData);//激发流程引擎流转到下一状态
               scheduleService.RunWorkflow(instance.InstanceId);
               //while (true)
                //{
                //    string stateName = workflowinstance.CurrentStateName;

                //    if (stateName != null && stateName.ToUpper().IndexOf("START") == -1)
                //    {
                //        break;
                //    }
                //}
                //System.Threading.Thread.Sleep(1000);
               if (instance == null)
               {
                   return "EndFlow";
               }
               StateMachineWorkflowInstance workflowinstance1 = new StateMachineWorkflowInstance(WfRuntime, instance.InstanceId);
               return  workflowinstance1.CurrentStateName;
               //return GetNextState(WfRuntime, instance, CurrentStateName);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("GetNextStateByEvent异常信息 :" + ex.ToString());
                throw new Exception(ex.Message);
            }
        }
コード例 #4
0
ファイル: SMTWorkFlowManage.cs プロジェクト: JuRogn/OA
 /// <summary>
 /// 获取当前实例的状态代码
 /// </summary>
 /// <param name="WfRuntime"></param>
 /// <param name="instance"></param>
 /// <param name="CurrentStateName"></param>
 /// <returns></returns>
 public static string GetNextState(WorkflowRuntime WfRuntime, WorkflowInstance instance, string CurrentStateName)
 {
     try
     {
         string StateName = CurrentStateName;
         LogHelper.WriteLog("循环获取当前实例的状态代码  (开始)instance=" + (instance != null ? instance.InstanceId.ToString() : "null") + " StateName=" + StateName);
         while (StateName == CurrentStateName)
         {
             if (instance == null)
             {
                 StateName = "EndFlow";
                 return StateName;
             }
             StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(WfRuntime, instance.InstanceId);
             StateName = workflowinstance.CurrentStateName;
         }
         LogHelper.WriteLog("循环获取当前实例的状态代码  (结束)instance=" + (instance != null ? instance.InstanceId.ToString() : "null") + " StateName=" + StateName);
         return StateName;
     }
     catch (Exception ex)
     {
         LogHelper.WriteLog("GetNextState异常信息 :" + ex.ToString());
         throw new Exception(ex.Message);
     }
 }
コード例 #5
0
ファイル: SMTWorkFlowManage.cs プロジェクト: JuRogn/OA
        /// <summary>
        /// 克隆一个实例
        /// </summary>
        /// <param name="WfRuntimeClone"></param>
        /// <param name="instanceClone"></param>
        /// <param name="WfRuntime"></param>
        /// <returns></returns>
        public static WorkflowInstance CloneWorkflowInstance(WorkflowRuntime WfRuntimeClone, WorkflowInstance instanceClone, WorkflowRuntime WfRuntime)
        {
            try
            {
                if (!WfRuntimeClone.IsStarted)
                {
                    WfRuntimeClone.StartRuntime();
                }
                StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(WfRuntimeClone, instanceClone.InstanceId);

                System.Workflow.Activities.StateMachineWorkflowActivity smworkflow = new StateMachineWorkflowActivity();
                smworkflow = workflowinstance.StateMachineWorkflow;
                RuleDefinitions ruleDefinitions = smworkflow.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions;
                WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer();

                StringBuilder xoml = new StringBuilder();
                StringBuilder rule = new StringBuilder();
                XmlWriter xmlWriter = XmlWriter.Create(xoml);
                XmlWriter ruleWriter = XmlWriter.Create(rule);
                markupSerializer.Serialize(xmlWriter, smworkflow);

                if (ruleDefinitions != null)
                    markupSerializer.Serialize(ruleWriter, ruleDefinitions);

                xmlWriter.Close();
                ruleWriter.Close();

                StringReader readxoml = new StringReader(xoml.ToString());
                XmlReader readerxoml = XmlReader.Create(readxoml);
                WorkflowInstance instance;
                if (ruleDefinitions == null)
                    instance = WfRuntime.CreateWorkflow(readerxoml);
                else
                {
                    StringReader readrule = new StringReader(rule.ToString());
                    XmlReader readerrule = XmlReader.Create(readrule);
                    instance = WfRuntime.CreateWorkflow(readerxoml, readerrule, null);
                }

                instance.Start();
                return instance;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("CloneWorkflowInstance异常信息 :" + ex.ToString());
                throw new Exception(ex.Message);
            }

        }
コード例 #6
0
ファイル: WorkflowMediator.cs プロジェクト: UrviGandhi/IGRSS
        public static string GetWorkflowState(Guid instanceID)
        {
            //Check.ArgumentIsNotNull(instanceID, "instanceID");
            InitilizeRuntime();
            string result;
            StateMachineWorkflowInstance instance = null;

            try
            {
                instance = new StateMachineWorkflowInstance(Runtime, instanceID);
            }
            catch (InvalidOperationException)
            {
                // the workflow wasnt in the persistence store
                // so we can assume it isn't running
            }

            if (instance != null)
            {
                result = instance.CurrentStateName;
            }
            else
            {
                result = string.Empty;
            }

            return result;
        }
コード例 #7
0
ファイル: FlowBLL.cs プロジェクト: JuRogn/OA
        //下一审核人提交审核时调用方法
        /// <summary>
        /// 固定流程:下一审核人提交审核时调用方法
        /// </summary>
        /// <param name="submitData"></param>
        /// <param name="dataResult"></param>
        /// <param name="listDetail"></param>
        /// <returns></returns>
        public DataResult ApprovalFlow2(OracleConnection con, SubmitData submitData, DataResult dataResult, List<FLOW_FLOWRECORDDETAIL_T> listDetail, ref FlowUser user, ref string msg)
        {
            if (submitData.NextApprovalUser == null)
            {
                submitData.NextApprovalUser = new UserInfo();
            }
            ///针对会签,该次审核成功后是否跳转至下一状态
            bool isGotoNextState = true;
            // WorkflowRuntime workflowRuntime = null;
            WorkflowInstance instance = null;
            FLOW_FLOWRECORDDETAIL_T entity = new FLOW_FLOWRECORDDETAIL_T();
            entity.FLOW_FLOWRECORDMASTER_T = new FLOW_FLOWRECORDMASTER_T();

            try
            {
                #region Entity赋值
                List<FLOW_FLOWRECORDDETAIL_T> tmpEntity = listDetail.Where(c => (c.EDITUSERID == submitData.ApprovalUser.UserID || c.AGENTUSERID == submitData.ApprovalUser.UserID) && c.FLAG == "0").ToList();
                if (tmpEntity == null)
                {
                    dataResult.FlowResult = FlowResult.FAIL;
                    dataResult.Err = "没有找到待审核信息 FORMID=" + user.FormID + "\r\n";
                    user.TrackingMessage += "没有找到待审核信息 FORMID=" + user.FormID + "\r\n";
                   
                    return dataResult;
                }
                entity = tmpEntity[0];
                entity.EDITDATE = DateTime.Now;  //审批时间
                if (entity.AGENTUSERID == submitData.ApprovalUser.UserID)
                {
                    entity.AGENTEDITDATE = entity.EDITDATE;  //代理审批时审批时间与代理审批时间到致
                }

                entity.CONTENT = submitData.ApprovalContent;
                entity.CHECKSTATE = ((int)submitData.ApprovalResult).ToString();
                #endregion
                #region backup persisted workflow instanceState
                if (!string.IsNullOrEmpty(entity.FLOW_FLOWRECORDMASTER_T.INSTANCEID))
                {
                    String connStringPersistence = ConfigurationManager.ConnectionStrings["OracleConnection"].ConnectionString;//Data Source=172.30.50.110;Initial Catalog=WorkflowPersistence;Persist Security Info=True;User ID=sa;Password=fbaz2012;MultipleActiveResultSets=True";
                    string sql=string.Format("select * from instance_state where instance_id='{0}'", entity.FLOW_FLOWRECORDMASTER_T.INSTANCEID);
                    user.InstanceState = MsOracle.GetDataSetByConnection(connStringPersistence, sql);
                }
                #endregion
                //workflowRuntime.StartRuntime();
                user.TrackingMessage += "创建工作流运行时开始 FORMID=" + user.FormID + "\r\n";
                workflowRuntime = SMTWorkFlowManage.CreateWorkFlowRuntime(true);
                try
                {
                    instance = SMTWorkFlowManage.GetWorkflowInstance(workflowRuntime,entity.FLOW_FLOWRECORDMASTER_T.INSTANCEID);// workflowRuntime.GetWorkflow(new Guid(tmp[0].FLOW_FLOWRECORDMASTER_T.INSTANCEID));
                    user.TrackingMessage += "FormID=" + submitData.FormID + ";ApprovalFlow2(try)从持久化库[ 完成 ]恢复创建工作流实例ID=" + entity.FLOW_FLOWRECORDMASTER_T.INSTANCEID + "\r\n";
                    LogHelper.WriteLog("审核 FormID=" + user.FormID + " WorkflowInstance ID=" + instance.InstanceId.ToString());

                }
                catch (Exception exGetWorkflowInstance)
                {
                    #region 重新创建新流程,将新流程设置为当前状态。
                    try
                    {
                        user.TrackingMessage += "FormID=" + submitData.FormID + ";从持久化恢复工作流失败 SMTWorkFlowManage.GetWorkflowInstance(" + workflowRuntime.Name + ", " + entity.FLOW_FLOWRECORDMASTER_T.INSTANCEID + ");原因如下:\r\n" + exGetWorkflowInstance.ToString() + ";\r\n下面重新创建新流程,并将新流程设置为当前状态;\r\nGetFlowByModelName:submitData.ApprovalUser.DepartmentID=" + submitData.ApprovalUser.DepartmentID + ";OrgType='" + ((int)submitData.FlowType).ToString() + "'";

                        List<FLOW_MODELFLOWRELATION_T> MODELFLOWRELATION = GetFlowByModelName(con, entity.FLOW_FLOWRECORDMASTER_T.CREATECOMPANYID, entity.FLOW_FLOWRECORDMASTER_T.CREATEDEPARTMENTID, submitData.ModelCode, ((int)submitData.FlowType).ToString(), ref  user);

                        FLOW_MODELFLOWRELATION_T flowRelation = MODELFLOWRELATION[0];
                        FLOW_FLOWDEFINE_T flowDefine = flowRelation.FLOW_FLOWDEFINE_T;
                        instance = SMTWorkFlowManage.CreateWorkflowInstance(workflowRuntime , flowDefine.XOML, flowDefine.RULES);
                        user.TrackingMessage += "FormID=" + submitData.FormID + ";ApprovalFlow2(catch)完成重新创建工作流实例ID=" + instance.InstanceId + "\r\n";
                        StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(workflowRuntime, instance.InstanceId);
                        ManualWorkflowSchedulerService scheduleService = workflowRuntime.GetService(typeof(ManualWorkflowSchedulerService)) as ManualWorkflowSchedulerService;
                        scheduleService.RunWorkflow(workflowinstance.InstanceId);

                        workflowinstance.SetState(entity.STATECODE);

                        //System.Threading.Thread.Sleep(1000); //commented by alan 2012/9/7
                        instance = SMTWorkFlowManage.GetWorkflowInstance(workflowRuntime,instance.InstanceId.ToString());
                        user.TrackingMessage += "FormID=" + submitData.FormID + ";ApprovalFlow2(catch)从持久化库再恢复刚才创建工作流实例ID=" + instance.InstanceId + "\r\n";

                        entity.FLOW_FLOWRECORDMASTER_T.INSTANCEID = instance.InstanceId.ToString();
                        //FLOW_FLOWRECORDDETAIL_TDAL.UpdateMasterINSTANCEID(entity.FLOW_FLOWRECORDMASTER_T);
                        FLOW_FLOWRECORDMASTER_TDAL.UpdateMasterINSTANCEID(con, entity.FLOW_FLOWRECORDMASTER_T);

                    }
                    catch (Exception exNewInstance)
                    {
                        user.ErrorMsg += "重新创建新流程,将新流程设置为当前状态失败:FormID=" + submitData.FormID + "异常信息:\r\n" + exNewInstance.Message + "\r\n";
                        LogHelper.WriteLog("重新创建新流程,将新流程设置为当前状态失败:FormID=" + submitData.FormID + "FlowBLL->ApprovalFlow2" + exNewInstance.Message);
                        //Tracer.Debug("exNewInstance: -" + submitData.FormID + "--submitDataXML:" + submitData.XML + "-" + exNewInstance.InnerException + exNewInstance.Message);
                        throw new Exception("重新创建新流程,将新流程设置为当前状态失败,请联系管理!");
                    }
                    #endregion
                }
                user.TrackingMessage += "SMTWorkFlowManage.CreateWorkFlowRuntime(true)完成FORMID=" + user.FormID + " \r\n";


                #region 当前状态会签状态处理
                bool currentIsCountersign = false;
                string currentCountersignType = "0";

                Utility.IsCountersign(entity.FLOW_FLOWRECORDMASTER_T.ACTIVEROLE, entity.STATECODE, ref currentIsCountersign, ref currentCountersignType);
                if (currentIsCountersign)
                {
                    user.TrackingMessage += "状态会签状态处理 FORMID=" + user.FormID + "  \r\n";
                    if (currentCountersignType == "1")//一人通过即所有通过,可以跳转至下一状态
                    {
                        isGotoNextState = true;
                    }
                    else
                    {
                        ///该审核是会签的最后的审核人
                        if (entity.FLOW_FLOWRECORDMASTER_T.FLOW_FLOWRECORDDETAIL_T.Count == 1)
                        {
                            isGotoNextState = true;
                        }
                        else
                        {
                            isGotoNextState = false;
                        }
                    }
                    user.TrackingMessage += "状态会签状态处理完成 FORMID=" + user.FormID + " \r\n";
                }
                #endregion
                //不同意状态处理
                if (submitData.ApprovalResult == ApprovalResult.NoPass)
                {
                    user.TrackingMessage += "审核不通过状态处理(开始) FORMID=" + user.FormID + " \r\n";
                    #region
                    instance.Terminate("0");
                    entity.FLOW_FLOWRECORDMASTER_T.CHECKSTATE = "3"; //设为终审不通过
                    entity.FLOW_FLOWRECORDMASTER_T.EDITUSERID = submitData.ApprovalUser.UserID;
                    entity.FLOW_FLOWRECORDMASTER_T.EDITUSERNAME = submitData.ApprovalUser.UserName;
                    entity.FLOW_FLOWRECORDMASTER_T.EDITDATE = DateTime.Now;
                    user.TrackingMessage += "审核不通过【开始更新明细表】!FORMID=" + user.FormID;
                    //user.TrackingMessage += "entity.FLOWRECORDDETAILID" + entity.FLOWRECORDDETAILID + "\r\n";//
                    //user.TrackingMessage += "entity.STATECODE=" + entity.STATECODE + "\r\n";//
                    //user.TrackingMessage += "entity.PARENTSTATEID =" + entity.PARENTSTATEID + "\r\n";//
                    //user.TrackingMessage += "entity.CONTENT=" + entity.CONTENT + "\r\n";//
                    //user.TrackingMessage += "entity.CHECKSTATE=" + entity.CHECKSTATE + "\r\n";//同意:1,不同意:0 ,未处理:2,会签同意7,会签不同意8
                    //user.TrackingMessage += "entity.FLAG =" + entity.FLAG + "\r\n";//已审批:1,未审批:0
                    //user.TrackingMessage += " entity.CREATEUSERID =" + entity.CREATEUSERID + "\r\n";//
                    //user.TrackingMessage += "entity.CREATEUSERNAME="******"\r\n";//
                    //user.TrackingMessage += " entity.CREATECOMPANYID=" + entity.CREATECOMPANYID + "\r\n";//
                    //user.TrackingMessage += " entity.CREATEDEPARTMENTID =" + entity.CREATEDEPARTMENTID + "\r\n";//
                    //user.TrackingMessage += "entity.CREATEPOSTID=" + entity.CREATEPOSTID + "\r\n";//
                    //user.TrackingMessage += "entity.CREATEDATE=" + entity.CREATEDATE + "\r\n";//
                    //user.TrackingMessage += " entity.EDITUSERID=" + entity.EDITUSERID + "\r\n";//
                    //user.TrackingMessage += "entity.EDITUSERNAME="******"\r\n";//
                    //user.TrackingMessage += " entity.EDITCOMPANYID =" + entity.EDITCOMPANYID + "\r\n";//
                    //user.TrackingMessage += " entity.EDITDEPARTMENTID=" + entity.EDITDEPARTMENTID + "\r\n";//
                    //user.TrackingMessage += "entity.EDITPOSTID=" + entity.EDITPOSTID + "\r\n";//
                    //user.TrackingMessage += "entity.EDITDATE=" + entity.EDITDATE + "\r\n";//
                    //user.TrackingMessage += "entity.AGENTUSERID =" + entity.AGENTUSERID + "\r\n";//
                    //user.TrackingMessage += " entity.AGENTERNAME=" + entity.AGENTERNAME + "\r\n";//
                    //user.TrackingMessage += "entity.AGENTEDITDATE=" + entity.AGENTEDITDATE + "\r\n";//
                    //user.TrackingMessage += "submitData.NextStateCode=" + submitData.NextStateCode + "\r\n";//
                    //user.TrackingMessage += "submitData.NextApprovalUser.UserID=" + submitData.NextApprovalUser.UserID + "\r\n";//
                    //user.TrackingMessage += " entity.FLOW_FLOWRECORDMASTER_T.FLOWRECORDMASTERID=" + entity.FLOW_FLOWRECORDMASTER_T.FLOWRECORDMASTERID + "\r\n";//

                    
                    UpdateFlowRecord(con, entity, submitData.NextStateCode, submitData.NextApprovalUser.UserID);
                    user.TrackingMessage += "审核不通过【开始更新主表】!FORMID=" + user.FormID;
                    FLOW_FLOWRECORDMASTER_TDAL.Update(entity.FLOW_FLOWRECORDMASTER_T);
                    dataResult.CheckState = "3";//
                    dataResult.FlowResult = FlowResult.END;

                    if (currentIsCountersign)
                    {
                        #region 当前是会签状态,删除未审核记录
                        user.TrackingMessage += "审核不通过【当前是会签状态,删除未审核记录】!FORMID=" + user.FormID;
                        entity.FLOW_FLOWRECORDMASTER_T.FLOW_FLOWRECORDDETAIL_T
                                .Where(detail => detail.FLOWRECORDDETAILID != entity.FLOWRECORDDETAILID && detail.STATECODE == entity.STATECODE && detail.FLAG == "0")
                                .ToList().ForEach(item =>
                                {
                                    item.FLAG = "1";
                                    item.CHECKSTATE = "8";
                                    UpdateFlowRecord2(con, item);
                                });
                        #endregion
                    }

                    #endregion
                    user.TrackingMessage += "审核通过状态处理(完成) FORMID=" + user.FormID + " \r\n";

                }
                else
                {
                    if (!isGotoNextState)
                    {
                        user.TrackingMessage += "isGotoNextState开始 FORMID=" + user.FormID + " \r\n";
                        #region

                        UpdateFlowRecord2(con, entity);
                        dataResult.AppState = entity.STATECODE;
                        dataResult.FlowResult = FlowResult.SUCCESS;
                        dataResult.CheckState = "1";
                        #endregion
                        user.TrackingMessage += "isGotoNextState完成 FORMID=" + user.FormID + "\r\n";
                    }
                    else
                    {
                        user.TrackingMessage += "获取下一状态数据开始 FORMID=" + user.FormID + " \r\n";
                        #region 获取下一状态数据
                        List<string> User = new List<string>();
                        User.Add(entity.FLOW_FLOWRECORDMASTER_T.CREATEUSERID);
                        User.Add(submitData.ApprovalUser.UserID);

                        List<string> tmpPostID = new List<string>();
                        tmpPostID.Add(entity.FLOW_FLOWRECORDMASTER_T.CREATEPOSTID);
                        tmpPostID.Add(entity.EDITPOSTID);
                        GetUserByInstance2(entity.FLOW_FLOWRECORDMASTER_T.CREATECOMPANYID, workflowRuntime, instance, entity.FLOW_FLOWRECORDMASTER_T.ACTIVEROLE, submitData.XML, entity.STATECODE, User, tmpPostID, submitData.FlowType, ref dataResult, ref user);

                        if (dataResult.FlowResult == FlowResult.FAIL)
                        {
                            return dataResult;
                        }
                        submitData.NextStateCode = dataResult.AppState;
                        if (dataResult.IsCountersign)
                        {
                            #region
                            if (dataResult.FlowResult == FlowResult.Countersign)
                            {
                                if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                                {
                                    return dataResult;
                                }
                            }
                            else
                            {
                                if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                                {
                                    submitData.DictCounterUser = dataResult.DictCounterUser;
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            #region
                            if (dataResult.FlowResult == FlowResult.MULTIUSER)
                            {
                                if (submitData.NextApprovalUser == null || (Utility.GetString(submitData.NextApprovalUser.UserID) == "" || Utility.GetString(submitData.NextApprovalUser.UserName) == ""))
                                {
                                    return dataResult;
                                }
                            }
                            else
                            {
                                if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                                {
                                    submitData.NextApprovalUser = dataResult.UserInfo[0];
                                }
                            }
                            #endregion
                        }

                        #endregion

                        user.TrackingMessage += "获取下一状态数据完成 FORMID=" + user.FormID + "\r\n";


                        user.TrackingMessage += "单据会签情况开始 FORMID=" + user.FormID + "\r\n";
                        #region 对于单会签情况,需要将其他审核人的审核设为会签通过状态

                        if (currentIsCountersign && currentCountersignType == "1")
                        {
                            entity.FLOW_FLOWRECORDMASTER_T.FLOW_FLOWRECORDDETAIL_T
                               .Where(detail => detail.FLOWRECORDDETAILID != entity.FLOWRECORDDETAILID && detail.STATECODE == entity.STATECODE && detail.FLAG == "0")
                               .ToList().ForEach(item =>
                               {
                                   item.FLAG = "1";
                                   item.CHECKSTATE = "7";
                                   UpdateFlowRecord2(con, item);
                               });
                        }
                        #endregion
                        user.TrackingMessage += "单据会签情况完成 FORMID=" + user.FormID + "\r\n";

                        #region


                        FlowDataType.FlowData FlowData = new FlowDataType.FlowData();
                        FlowData.xml = submitData.XML;
                        workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                        {
                            instance = null;

                        };
                        user.TrackingMessage += "处理kpi 开始 FORMID=" + user.FormID + "\r\n";

                        #region 处理kpi时间
                        string KPITime = "";
                        //PerformanceServiceWS.PerformanceServiceClient psc = new PerformanceServiceWS.PerformanceServiceClient();
                        string pscResult = entity.FLOW_FLOWRECORDMASTER_T.KPITIMEXML;
                        //psc.Close();
                        if (!string.IsNullOrEmpty(pscResult))
                        {
                            XElement xe = XElement.Parse(pscResult);
                            Func<XElement, bool> f = (x) =>
                            {
                                XAttribute xid = x.Attribute("id");
                                XAttribute xvalue = x.Attribute("value");
                                if (xid == null || xvalue == null)
                                    return false;
                                else
                                {
                                    if (xid.Value == dataResult.AppState)
                                        return true;
                                    else return false;
                                }
                            };
                            XElement FlowNode = xe.Elements("FlowNode").FirstOrDefault(f);
                            if (FlowNode != null)
                            {
                                KPITime = FlowNode.Attribute("value").Value;
                            }
                        }
                        dataResult.KPITime = KPITime;

                        #endregion

                        user.TrackingMessage += "处理kpi 完成 FORMID=" + user.FormID + "\r\n";

                        if (!dataResult.IsCountersign)
                        {
                            user.TrackingMessage += "非会签 开始 FORMID=" + user.FormID + "\r\n";
                            #region  非会签

                            UserInfo AppUser = submitData.NextApprovalUser;
                            dataResult.UserInfo.Clear();
                            dataResult.UserInfo.Add(AppUser);
                            UserInfo AgentAppUser = GetAgentUserInfo(submitData.ModelCode, AppUser.UserID);//查询是否启用了代理人                            
                            dataResult = DoFlowRecord2(con, workflowRuntime, instance, entity, submitData.NextStateCode, AppUser, AgentAppUser, submitData.SubmitFlag, submitData.FlowType,ref user); //处理流程数据
                            dataResult.AgentUserInfo = AgentAppUser;
                            dataResult.IsCountersign = false;
                            #endregion
                            user.TrackingMessage += "非会签 完成 FORMID=" + user.FormID + "\r\n";
                        }
                        else
                        {
                            #region  会签

                            dataResult.DictCounterUser = submitData.DictCounterUser;
                            Dictionary<UserInfo, UserInfo> dictAgentUserInfo = GetAgentUserInfo2(submitData.ModelCode, submitData.DictCounterUser);
                            dataResult = DoFlowRecord_Approval(con, workflowRuntime, instance, entity, submitData.NextStateCode, submitData.DictCounterUser, dictAgentUserInfo, submitData.SubmitFlag, submitData.FlowType); //处理流程数据
                            dataResult.DictAgentUserInfo = dictAgentUserInfo;
                            dataResult.IsCountersign = true;


                            #endregion
                        }

                        user.TrackingMessage += "激发流程引擎执行到一下流程 开始 FORMID=" + user.FormID + "\r\n";
                        #region 激发流程引擎执行到一下流程
                        StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(workflowRuntime, instance.InstanceId);
                        ManualWorkflowSchedulerService scheduleService = workflowRuntime.GetService(typeof(ManualWorkflowSchedulerService)) as ManualWorkflowSchedulerService;
                        if (dataResult.AppState == null || dataResult.AppState == "")
                        {
                            scheduleService.RunWorkflow(workflowinstance.InstanceId);
                            workflowRuntime.GetService<FlowEvent>().OnDoFlow(instance.InstanceId, FlowData); //激发流程引擎执行到一下流程
                            scheduleService.RunWorkflow(workflowinstance.InstanceId);

                        }
                        else
                        {
                            string ss = "";
                            int n = 0;
                            scheduleService.RunWorkflow(workflowinstance.InstanceId);

                            workflowinstance.SetState(dataResult.AppState); //流程跳转到指定节点
                            //while (true)
                            //{
                            //    ss += (n++).ToString()+"|" + workflowinstance.CurrentStateName;
                            //    string stateName = workflowinstance.CurrentStateName;

                            //    if (stateName != null && stateName.ToUpper().IndexOf("START") == -1)
                            //    {
                            //        break;
                            //    }
                            //}
                        }
                        #endregion
                        user.TrackingMessage += "激发流程引擎执行到一下流程 完成 FORMID=" + user.FormID + "\r\n";
                        //dataResult.CanSendMessage = true;

                        user.TrackingMessage += "System.Threading.Thread.Sleep(1000)\r\n";
                       //System.Threading.Thread.Sleep(1000); //Commented by Alan 2012-7-25 ,使用手动ScheduleService运行工作流,此处不需要
                        if (submitData.FlowType == FlowType.Task)
                            dataResult.SubModelCode = Utility.GetSubModelCode(entity.FLOW_FLOWRECORDMASTER_T.ACTIVEROLE, dataResult.AppState); //返回下一子模块代码
                        user.TrackingMessage += "System.Threading.Thread.Sleep(1000)完成\r\n";

                        #endregion
                    }


                }
                dataResult.CurrentIsCountersign = currentIsCountersign;
                dataResult.IsGotoNextState = isGotoNextState;
                return dataResult;
            }
            catch (Exception e)
            {
                user.ErrorMsg += "提交审核时出错!FORMID=" + user.FormID + " 异常信息:" + e.ToString()+ "\r\n";
                LogHelper.WriteLog("提交审核时出错!FORMID=" + user.FormID + " 异常信息:" + e.ToString());
                throw new Exception("提交审核时出错,请联系管理员! \r\n FormID=" + user.FormID + "");
            }
            finally
            {

                entity = null;
                instance = null;
                SMTWorkFlowManage.ColseWorkFlowRuntime(workflowRuntime);
            }
        }
コード例 #8
0
ファイル: Mainform.cs プロジェクト: spzenk/sfdocsamples
        private Guid StartOrderWorkflow()
        {
            // NOTE:  "Late-binding to the OrderWorkflows" assembly so we
            // ...can easily copy this exe and project into another soluton

            // Load the OrderWorkflows assembly
            Assembly orderWorkflowsAssembly =
                Assembly.Load("OrderWorkflows");

            // Get a reference to the System.Type for the OrderWorkflows.Workflow1
            Type workflowType = orderWorkflowsAssembly.GetType("Microsoft.Samples.Workflow.OrderApplication.SampleWorkflow");

            if (workflowType == null) return Guid.Empty;

            WorkflowInstance instance = runtime.CreateWorkflow(workflowType);

            StateMachineWorkflowInstance stateMachineInstance = new StateMachineWorkflowInstance(runtime, instance.InstanceId);

            instance.Start();

            // Add the StateMachineInstance object for our Workflow to our dictionary
            this.stateMachineInstances.Add(instance.InstanceId.ToString(), stateMachineInstance);

            // Return the WorkflowInstanceId
            return instance.InstanceId;
        }
コード例 #9
0
ファイル: FlowBLL2.cs プロジェクト: JuRogn/OA
        /// <summary>
        /// 新增流程(对数据库操作)
        /// </summary>
        /// <param name="ApprovalData"></param>
        /// <param name="APPDataResult"></param>
        /// <returns></returns>    
        public DataResult AddFlow2(OracleConnection con, SubmitData submitData, DataResult dataResult, ref string msg)
        {
            // WorkflowRuntime workflowRuntime = null;
            WorkflowInstance instance = null;


            try
            {
                msg += "获取定义的流程" + DateTime.Now.ToString() + "\r\n";
                #region 获取定义的流程
                LogHelper.WriteLog("获取定义的流程.GetFlowByModelName:submitData.ApprovalUser.DepartmentID=" + submitData.ApprovalUser.DepartmentID + ";OrgType='" + ((int)submitData.FlowType).ToString() + "'");
                List<FLOW_MODELFLOWRELATION_T> MODELFLOWRELATION = GetFlowByModelName(con, submitData.ApprovalUser.CompanyID, submitData.ApprovalUser.DepartmentID, submitData.ModelCode, ((int)submitData.FlowType).ToString());//对数据库操作
                if (MODELFLOWRELATION == null || MODELFLOWRELATION.Count == 0)
                {
                    dataResult.FlowResult = FlowResult.FAIL;
                    dataResult.Err = "没有找到可使用的流程";
                    return dataResult;
                }
                msg += "获取定义的流程完成" + DateTime.Now.ToString() + "\r\n";
                #endregion
                FLOW_MODELFLOWRELATION_T flowRelation = MODELFLOWRELATION[0];
                FLOW_FLOWDEFINE_T flowDefine = flowRelation.FLOW_FLOWDEFINE_T;
                if (flowDefine.RULES != null && flowDefine.RULES.Trim() == "")
                {
                    flowDefine.RULES = null;
                }
                //if (string.IsNullOrEmpty(flowDefine.RULES.Trim()))
                //{
                //    flowDefine.RULES = null;
                //}
                msg += " SMTWorkFlowManage.CreateWorkFlowRuntime(true)" + DateTime.Now.ToString() + "\r\n";
                workflowRuntime = SMTWorkFlowManage.CreateWorkFlowRuntime(true);
                instance = SMTWorkFlowManage.CreateWorkflowInstance(workflowRuntime, flowDefine.XOML, flowDefine.RULES);
                LogHelper.WriteLog("AddFlow2创建工作流实例ID=" + instance.InstanceId);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                {
                    instance = null;

                };
                msg += " SMTWorkFlowManage.CreateWorkFlowRuntime(true)完成" + DateTime.Now.ToString() + "\r\n";
                #region master赋值
                FLOW_FLOWRECORDMASTER_T master = new FLOW_FLOWRECORDMASTER_T();
                master.INSTANCEID = instance.InstanceId.ToString();
                master.BUSINESSOBJECT = submitData.XML;
                master.FORMID = submitData.FormID;
                master.MODELCODE = submitData.ModelCode;
                master.ACTIVEROLE = Utility.GetActiveRlue(flowDefine.LAYOUT);
                master.FLOWTYPE = ((int)submitData.FlowType).ToString();
                master.FLOWSELECTTYPE = ((int)submitData.FlowSelectType).ToString();
                master.FLOWCODE = flowDefine.FLOWCODE;
                #endregion

                #region 获取下一状态数据
                msg += " 获取下一状态数据" + DateTime.Now.ToString() + "\r\n";
                DateTime star = DateTime.Now;
                GetUserByFlow2(submitData.ApprovalUser.CompanyID, flowDefine.XOML, flowDefine.RULES, master.ACTIVEROLE, submitData.XML, submitData.ApprovalUser.UserID, submitData.ApprovalUser.PostID, submitData.FlowType, ref dataResult, ref msg);
                DateTime end = DateTime.Now;
                msg += " 获取下一状态数据完成" + DateTime.Now.ToString() + "\r\n";
                string str = Service2.DateDiff(end, star);
                if (dataResult.FlowResult == FlowResult.FAIL)
                {
                    return dataResult;
                }
                submitData.NextStateCode = dataResult.AppState;
                if (dataResult.IsCountersign)
                {
                    #region
                    if (dataResult.FlowResult == FlowResult.Countersign)
                    {
                        if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                        {
                            return dataResult;
                        }
                    }
                    else
                    {
                        if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                        {
                            submitData.DictCounterUser = dataResult.DictCounterUser;
                        }
                    }
                    #endregion
                }
                else
                {
                    #region
                    if (dataResult.FlowResult == FlowResult.MULTIUSER)
                    {
                        if (submitData.NextApprovalUser == null || (Utility.GetString(submitData.NextApprovalUser.UserID) == "" || Utility.GetString(submitData.NextApprovalUser.UserName) == ""))
                        {
                            return dataResult;
                        }
                    }
                    else
                    {
                        if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                        {
                            submitData.NextApprovalUser = dataResult.UserInfo[0];
                        }
                    }
                    #endregion
                }

                #endregion

                #region 实体赋值
                FLOW_FLOWRECORDDETAIL_T entity = new FLOW_FLOWRECORDDETAIL_T();
                entity.FLOW_FLOWRECORDMASTER_T = master;
                entity.CREATECOMPANYID = submitData.ApprovalUser.CompanyID;
                entity.CREATEDEPARTMENTID = submitData.ApprovalUser.DepartmentID;
                entity.CREATEPOSTID = submitData.ApprovalUser.PostID;
                entity.CREATEUSERID = submitData.ApprovalUser.UserID;
                entity.CREATEUSERNAME = submitData.ApprovalUser.UserName;
                #endregion
                msg += " 处理kpi时间" + DateTime.Now.ToString() + "\r\n";
                #region 处理kpi时间
                string KPITime = "";
                #region 加入缓存
                string pscResult = CacheProvider.GetCache<string>(flowRelation.MODELFLOWRELATIONID);
                if (string.IsNullOrEmpty(pscResult))
                {
                    PerformanceServiceWS.PerformanceServiceClient psc = new PerformanceServiceWS.PerformanceServiceClient();
                    pscResult = psc.GetKPIPointsByBusinessCode(flowRelation.MODELFLOWRELATIONID);//调用服务
                    CacheProvider.Add<string>(flowRelation.MODELFLOWRELATIONID, pscResult);
                    psc.Close();
                }
                #endregion
                //PerformanceServiceWS.PerformanceServiceClient psc = new PerformanceServiceWS.PerformanceServiceClient();
                //string pscResult = psc.GetKPIPointsByBusinessCode(flowRelation.MODELFLOWRELATIONID);//调用服务
                //psc.Close();
                if (!string.IsNullOrEmpty(pscResult))
                {
                    XElement xe = XElement.Parse(pscResult);
                    Func<XElement, bool> f = (x) =>
                    {
                        XAttribute xid = x.Attribute("id");
                        XAttribute xvalue = x.Attribute("value");
                        if (xid == null || xvalue == null)
                            return false;
                        else
                        {
                            if (xid.Value == dataResult.AppState)
                                return true;
                            else return false;
                        }
                    };
                    XElement FlowNode = xe.Elements("FlowNode").FirstOrDefault(f);
                    if (FlowNode != null)
                    {
                        KPITime = FlowNode.Attribute("value").Value;
                    }
                }

                dataResult.KPITime = KPITime;
                master.KPITIMEXML = pscResult;
                #endregion
                msg += " 处理kpi时间完成" + DateTime.Now.ToString() + "\r\n";
                FlowDataType.FlowData FlowData = new FlowDataType.FlowData();
                FlowData.xml = submitData.XML;

                if (!dataResult.IsCountersign)
                {
                    #region  非会签
                    UserInfo AppUser = new UserInfo(); //下一审核人
                    AppUser = submitData.NextApprovalUser;
                    dataResult.UserInfo.Clear();
                    dataResult.UserInfo.Add(AppUser);
                    UserInfo AgentAppUser = GetAgentUserInfo(submitData.ModelCode, AppUser.UserID);//查询是否启用了代理人                    
                    dataResult = DoFlowRecord2(con, workflowRuntime, instance, entity, submitData.NextStateCode, AppUser, AgentAppUser, submitData.SubmitFlag, submitData.FlowType); //处理流程数据
                    dataResult.IsCountersign = false;
                    dataResult.AgentUserInfo = AgentAppUser;
                    #endregion
                }
                else
                {
                    msg += " 会签" + DateTime.Now.ToString() + "\r\n";
                    #region  会签
                    //Tracer.Debug("-----DoFlowRecord_Add:" + DateTime.Now.ToString()+"\n");
                    dataResult.DictCounterUser = submitData.DictCounterUser;
                    Dictionary<UserInfo, UserInfo> dictAgentUserInfo = GetAgentUserInfo2(submitData.ModelCode, submitData.DictCounterUser);
                    dataResult = DoFlowRecord_Add(con, workflowRuntime, instance, entity, submitData.NextStateCode, submitData.DictCounterUser, dictAgentUserInfo, submitData.SubmitFlag, submitData.FlowType); //处理流程数据
                    //Tracer.Debug("-----DoFlowRecord_AddEnd:" + DateTime.Now.ToString()+"\n");
                    dataResult.IsCountersign = true;
                    dataResult.DictAgentUserInfo = dictAgentUserInfo;
                    #endregion
                    msg += "会签完成" + DateTime.Now.ToString() + "\r\n";
                }
                msg += "激发流程引擎执行到一下流程" + DateTime.Now.ToString() + "\r\n";
                #region 激发流程引擎执行到一下流程
                string ss = "";
                int n = 0;
                if (dataResult.AppState == null || dataResult.AppState == "")
                {
                    msg += " workflowRuntime.GetService<FlowEvent>()" + DateTime.Now.ToString() + "\r\n";
                    workflowRuntime.GetService<FlowEvent>().OnDoFlow(instance.InstanceId, FlowData); //激发流程引擎执行到一下流程
                    msg += " workflowRuntime.GetService<FlowEvent>()完成" + DateTime.Now.ToString() + "\r\n";
                }
                else
                {
                    StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(workflowRuntime, instance.InstanceId);

                    workflowinstance.SetState(dataResult.AppState); //流程跳转到指定节点

                    while (true)
                    {

                        ss += (n++).ToString() + "|" + workflowinstance.CurrentStateName + "\r\n";
                        string stateName = workflowinstance.CurrentStateName;
                        if (stateName != null && stateName.ToUpper().IndexOf("STATE") >= 0)
                        {
                            break;
                        }

                    }
                }

                #endregion
                msg += "激发流程引擎执行到一下流程完成" + DateTime.Now.ToString() + "\r\n";
                msg += "System.Threading.Thread.Sleep(1000)" + DateTime.Now.ToString() + "\r\n";
                //System.Threading.Thread.Sleep(1000);//当前用到
                dataResult.ModelFlowRelationID = flowRelation.MODELFLOWRELATIONID; //返回关联ID
                dataResult.KPITime = KPITime;
                //dataResult.CanSendMessage = true;
                if (submitData.FlowType == FlowType.Task)
                {
                    dataResult.SubModelCode = Utility.GetSubModelCode(master.ACTIVEROLE, dataResult.AppState); //返回下一子模块代码
                }
                msg += "System.Threading.Thread.Sleep(1000)完成" + DateTime.Now.ToString() + "\r\n";
                return dataResult;
            }

            catch (Exception e)
            {

                throw new Exception(e.Message);
            }
            finally
            {

                instance = null;
                SMTWorkFlowManage.ColseWorkFlowRuntime(workflowRuntime);
            }


        }
コード例 #10
0
ファイル: FlowBLL2.cs プロジェクト: JuRogn/OA
        /// <summary>
        /// 获取工作流状态
        /// </summary>
        /// <param name="workflowRuntime">工作流运行时</param>
        /// <param name="instance">工作流实例</param>
        /// <returns></returns>
        public static string GetState(WorkflowRuntime workflowRuntime, WorkflowInstance instance, string CurrentStateName)
        {
            string StateName = CurrentStateName;

            while (StateName == CurrentStateName)
            {
                StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(workflowRuntime, instance.InstanceId);
                StateName = workflowinstance.CurrentStateName;

                StateName = StateName == null ? "EndFlow" : StateName;
            }
            //System.Threading.Thread.Sleep(1 * 1000);
            //ReadOnlyCollection<WorkflowQueueInfo> queueInfoData = instance.GetWorkflowQueueData();
            //if (queueInfoData.Count != 0)
            //{

            //    foreach (WorkflowQueueInfo info in queueInfoData)
            //    {
            //        if (info.QueueName.Equals("SetStateQueue"))
            //        {

            //            StateName = info.SubscribedActivityNames[0];
            //        }
            //    }

            //}
            return StateName;

        }
コード例 #11
0
        public IEnumerable<string> GetCurrentFormEvents(Guid instanceId)
        {
            DoInitialize(0);

            IEnumerable<string> eventNames = new StateMachineWorkflowInstance(WorkflowFacade.WorkflowRuntime, instanceId).GetCurrentEventNames(typeof(IFormsWorkflowEventService));

            return eventNames;
        }
コード例 #12
0
        public void SetWorkflowState(Guid instanceId, ServiceIdentity serviceIdentity, string stateName, string comment)
        {
            var workflowState = WorkflowStateService.GetWorkflowState(instanceId);


            if (workflowState.WorkflowStateName != stateName || workflowState.IsInitial)
            //Для черновиков устанавливаем всегда это временно
            {
                WorkflowSupportService.TryUpgradeWorkflow(Runtime, instanceId);

                WorkflowParcelService.AddParcel(instanceId,
                                                new WorkflowSetStateParcel()
                                                {
                                                    Comment = comment,
                                                    InitiatorId = serviceIdentity.Id,
                                                    Command = WorkflowCommand.Unknown,
                                                    PreviousWorkflowState = workflowState
                                                });
                bool isIdled = true;
                using (var sync = new WorkflowSync(Runtime, instanceId))
                {
                    if (!WorkflowSupportService.CreateWorkflowIfNotExists(Runtime, instanceId, workflowState.Type))
                    //Это ожидание создания воркфлоу
                    {
                        sync.WaitHandle.WaitOne(600000);
                        isIdled = sync.WasIdled;
                    }

                }
                //Если воркфлоу не стало идленым - то его необходимо удалить полностью и создать заново
                if (!isIdled)
                {
                    using (var context = this.CreateContext())
                    {
                        context.DeleteWorkflowInPesistenceStore(instanceId);
                        context.SubmitChanges();
                    }
                    using (var sync = new WorkflowSync(Runtime, instanceId))
                    {
                        if (!WorkflowSupportService.CreateWorkflowIfNotExists(Runtime, instanceId, workflowState.Type))
                        //Это ожидание создания воркфлоу
                        {
                            sync.WaitHandle.WaitOne(600000);
                        }

                    }
                }

                var instance = new StateMachineWorkflowInstance(Runtime, instanceId);
                var newWorkflowState = WorkflowStateService.GetWorkflowState(instanceId);
                if (newWorkflowState.WorkflowStateName != stateName)
                {
                    using (var sync = new WorkflowSync(Runtime, instanceId))
                    //Это ожидание завершения установки состояния воркфлоу
                    {
                        instance.SetState(stateName);
                        sync.WaitHandle.WaitOne(600000);
                    }
                }
                WorkflowState state =
                    WorkflowState.AllStates.First(
                        ws => ws.WorkflowStateName == stateName && ws.Type.Id == workflowState.Type.Id);
                if (!state.IsFinal && !state.IsInitial)
                    WorkflowSupportService.RewriteWorkflow(instanceId, state);
                //Для РД удаляем историю согласования
                if (workflowState.Type == WorkflowType.BillDemandWorkfow)
                {
                    if (state == WorkflowState.BillLimitManagerSighting)
                    {
                        BillDemandBuinessService.LimitExecutorResetSights(instanceId);
                    }

                    BillDemandBuinessService.LimitExecutorResetSights(instanceId);
                    BillDemandBuinessService.LimitManagerResetSights(instanceId);
                }

            }
        }
コード例 #13
0
        private static void PrintStateMachineState(WorkflowRuntime runtime, Guid instanceID)
        {
            StateMachineWorkflowInstance myInstance =
               new StateMachineWorkflowInstance(runtime, instanceID);

            Console.WriteLine("Workflow GUID: {0}", instanceID);
            Console.WriteLine("Current State: {0}", myInstance.CurrentStateName);
            Console.WriteLine("Transition States Available: {0}",
               myInstance.PossibleStateTransitions.Count);
            foreach (string transition in myInstance.PossibleStateTransitions)
            {
                Console.WriteLine("Transition to -> {0}", transition);
            }
            Console.WriteLine("\n\n------------------\n");
        }
コード例 #14
0
 private static void PrintHistory(WorkflowRuntime runtime,Guid instanceID)
 {
     StateMachineWorkflowInstance instance = new StateMachineWorkflowInstance(runtime, instanceID);
     Console.WriteLine("History of State Machine instance's workflow: (From Last to First)");
     foreach (string history in instance.StateHistory)
     {
         Console.WriteLine("\t{0}", history);
     }
     Console.WriteLine("\n\n------------------\n");
 }
コード例 #15
0
ファイル: Form1.cs プロジェクト: spzenk/sfdocsamples
 private void btnStartWorkflow_Click(object sender, EventArgs e)
 {
     // Start the Workflow
     stateMachineInstance = this.StartSpeechWorkflow();
 }
コード例 #16
0
ファイル: FlowBLL2.cs プロジェクト: JuRogn/OA
        //下一审核人提交审核时调用方法
        /// <summary>
        /// 下一审核人提交审核时调用方法
        /// </summary>
        /// <param name="submitData"></param>
        /// <param name="dataResult"></param>
        /// <param name="listDetail"></param>
        /// <returns></returns>
        public DataResult ApprovalFlow2(OracleConnection con, SubmitData submitData, DataResult dataResult, List<FLOW_FLOWRECORDDETAIL_T> listDetail, ref string msg)
        {
            ///针对会签,该次审核成功后是否跳转至下一状态
            bool isGotoNextState = true;
            // WorkflowRuntime workflowRuntime = null;
            WorkflowInstance instance = null;
            FLOW_FLOWRECORDDETAIL_T entity = new FLOW_FLOWRECORDDETAIL_T();
            entity.FLOW_FLOWRECORDMASTER_T = new FLOW_FLOWRECORDMASTER_T();

            try
            {
                #region Entity赋值
                List<FLOW_FLOWRECORDDETAIL_T> tmpEntity = listDetail.Where(c => (c.EDITUSERID == submitData.ApprovalUser.UserID || c.AGENTUSERID == submitData.ApprovalUser.UserID) && c.FLAG == "0").ToList();
                if (tmpEntity == null)
                {
                    dataResult.FlowResult = FlowResult.FAIL;
                    dataResult.Err = "没有找到待审核信息";
                    return dataResult;
                }
                entity = tmpEntity[0];
                entity.EDITDATE = DateTime.Now;  //审批时间
                if (entity.AGENTUSERID == submitData.ApprovalUser.UserID)
                {
                    entity.AGENTEDITDATE = entity.EDITDATE;  //代理审批时审批时间与代理审批时间到致
                }

                entity.CONTENT = submitData.ApprovalContent;
                entity.CHECKSTATE = ((int)submitData.ApprovalResult).ToString();
                #endregion

                //workflowRuntime.StartRuntime();
                msg += "SMTWorkFlowManage.CreateWorkFlowRuntime(true)" + DateTime.Now.ToString() + "\r\n";
                workflowRuntime = SMTWorkFlowManage.CreateWorkFlowRuntime(true);
                try
                {
                    instance = SMTWorkFlowManage.GetWorkflowInstance(workflowRuntime, entity.FLOW_FLOWRECORDMASTER_T.INSTANCEID);// workflowRuntime.GetWorkflow(new Guid(tmp[0].FLOW_FLOWRECORDMASTER_T.INSTANCEID));
                    LogHelper.WriteLog("FormID=" + submitData.FormID + ";ApprovalFlow2(try)从持久化库[ 完成 ]恢复创建工作流实例ID=" + entity.FLOW_FLOWRECORDMASTER_T.INSTANCEID);


                }
                catch (Exception exGetWorkflowInstance)
                {
                    #region 重新创建新流程,将新流程设置为当前状态。
                    try
                    {
                        string exc = "FormID=" + submitData.FormID + ";从持久化恢复工作流失败 SMTWorkFlowManage.GetWorkflowInstance(" + workflowRuntime.Name + ", " + entity.FLOW_FLOWRECORDMASTER_T.INSTANCEID + ");原因如下:\r\n" + exGetWorkflowInstance.ToString() + ";\r\n下面重新创建新流程,并将新流程设置为当前状态;\r\nGetFlowByModelName:submitData.ApprovalUser.DepartmentID=" + submitData.ApprovalUser.DepartmentID + ";OrgType='" + ((int)submitData.FlowType).ToString() + "'";
                        LogHelper.WriteLog(exc);

                        List<FLOW_MODELFLOWRELATION_T> MODELFLOWRELATION = GetFlowByModelName(con, entity.FLOW_FLOWRECORDMASTER_T.CREATECOMPANYID, entity.FLOW_FLOWRECORDMASTER_T.CREATEDEPARTMENTID, submitData.ModelCode, ((int)submitData.FlowType).ToString());

                        FLOW_MODELFLOWRELATION_T flowRelation = MODELFLOWRELATION[0];
                        FLOW_FLOWDEFINE_T flowDefine = flowRelation.FLOW_FLOWDEFINE_T;
                        instance = SMTWorkFlowManage.CreateWorkflowInstance(workflowRuntime, flowDefine.XOML, flowDefine.RULES);
                        LogHelper.WriteLog("FormID=" + submitData.FormID + ";ApprovalFlow2(catch)完成重新创建工作流实例ID=" + instance.InstanceId);
                        StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(workflowRuntime, instance.InstanceId);
                        workflowinstance.SetState(entity.STATECODE);
                        System.Threading.Thread.Sleep(1000);
                        instance = SMTWorkFlowManage.GetWorkflowInstance(workflowRuntime, instance.InstanceId.ToString());
                        LogHelper.WriteLog("FormID=" + submitData.FormID + ";ApprovalFlow2(catch)从持久化库再恢复刚才创建工作流实例ID=" + instance.InstanceId);

                        entity.FLOW_FLOWRECORDMASTER_T.INSTANCEID = instance.InstanceId.ToString();
                        //FLOW_FLOWRECORDDETAIL_TDAL.UpdateMasterINSTANCEID(entity.FLOW_FLOWRECORDMASTER_T);
                        FLOW_FLOWRECORDMASTER_TDAL.UpdateMasterINSTANCEID(con, entity.FLOW_FLOWRECORDMASTER_T);

                    }
                    catch (Exception exNewInstance)
                    {
                        LogHelper.WriteLog("重新创建新流程,将新流程设置为当前状态失败:FormID=" + submitData.FormID + "FlowBll2->ApprovalFlow2" + exNewInstance.Message);
                        //Tracer.Debug("exNewInstance: -" + submitData.FormID + "--submitDataXML:" + submitData.XML + "-" + exNewInstance.InnerException + exNewInstance.Message);
                        throw exGetWorkflowInstance;
                    }
                    #endregion
                }
                msg += "SMTWorkFlowManage.CreateWorkFlowRuntime(true)完成" + DateTime.Now.ToString() + "\r\n";


                #region 当前状态会签状态处理
                bool currentIsCountersign = false;
                string currentCountersignType = "0";

                Utility.IsCountersign(entity.FLOW_FLOWRECORDMASTER_T.ACTIVEROLE, entity.STATECODE, ref currentIsCountersign, ref currentCountersignType);
                if (currentIsCountersign)
                {
                    msg += "状态会签状态处理" + DateTime.Now.ToString() + "\r\n";
                    if (currentCountersignType == "1")//一人通过即所有通过,可以跳转至下一状态
                    {
                        isGotoNextState = true;
                    }
                    else
                    {
                        ///该审核是会签的最后的审核人
                        if (entity.FLOW_FLOWRECORDMASTER_T.FLOW_FLOWRECORDDETAIL_T.Count == 1)
                        {
                            isGotoNextState = true;
                        }
                        else
                        {
                            isGotoNextState = false;
                        }
                    }
                    msg += "状态会签状态处理完成" + DateTime.Now.ToString() + "\r\n";
                }
                #endregion
                //不同意状态处理
                if (submitData.ApprovalResult == ApprovalResult.NoPass)
                {
                    msg += "不同意状态处理" + DateTime.Now.ToString() + "\r\n";
                    #region
                    instance.Terminate("0");
                    entity.FLOW_FLOWRECORDMASTER_T.CHECKSTATE = "3"; //设为终审不通过
                    entity.FLOW_FLOWRECORDMASTER_T.EDITUSERID = submitData.ApprovalUser.UserID;
                    entity.FLOW_FLOWRECORDMASTER_T.EDITUSERNAME = submitData.ApprovalUser.UserName;
                    entity.FLOW_FLOWRECORDMASTER_T.EDITDATE = DateTime.Now;
                    UpdateFlowRecord(con, entity, submitData.NextStateCode, submitData.NextApprovalUser.UserID);
                    FLOW_FLOWRECORDMASTER_TDAL.Update(entity.FLOW_FLOWRECORDMASTER_T);
                    dataResult.CheckState = "3";//
                    dataResult.FlowResult = FlowResult.END;

                    if (currentIsCountersign)
                    {
                        #region 当前是会签状态,删除未审核记录
                        entity.FLOW_FLOWRECORDMASTER_T.FLOW_FLOWRECORDDETAIL_T
                                .Where(detail => detail.FLOWRECORDDETAILID != entity.FLOWRECORDDETAILID && detail.STATECODE == entity.STATECODE && detail.FLAG == "0")
                                .ToList().ForEach(item =>
                                {
                                    item.FLAG = "1";
                                    item.CHECKSTATE = "8";
                                    UpdateFlowRecord2(con, item);
                                });
                        #endregion
                    }

                    #endregion
                    msg += "不同意状态处理完成" + DateTime.Now.ToString() + "\r\n";

                }
                else
                {
                    if (!isGotoNextState)
                    {
                        msg += "isGotoNextState" + DateTime.Now.ToString() + "\r\n";
                        #region

                        UpdateFlowRecord2(con, entity);
                        dataResult.AppState = entity.STATECODE;
                        dataResult.FlowResult = FlowResult.SUCCESS;
                        dataResult.CheckState = "1";
                        #endregion
                        msg += "isGotoNextState完成" + DateTime.Now.ToString() + "\r\n";
                    }
                    else
                    {
                        msg += "获取下一状态数据" + DateTime.Now.ToString() + "\r\n";
                        #region 获取下一状态数据
                        List<string> User = new List<string>();
                        User.Add(entity.FLOW_FLOWRECORDMASTER_T.CREATEUSERID);
                        User.Add(submitData.ApprovalUser.UserID);

                        List<string> tmpPostID = new List<string>();
                        tmpPostID.Add(entity.FLOW_FLOWRECORDMASTER_T.CREATEPOSTID);
                        tmpPostID.Add(entity.EDITPOSTID);
                        GetUserByInstance2(entity.FLOW_FLOWRECORDMASTER_T.CREATECOMPANYID, workflowRuntime, instance, entity.FLOW_FLOWRECORDMASTER_T.ACTIVEROLE, submitData.XML, entity.STATECODE, User, tmpPostID, submitData.FlowType, ref dataResult);

                        if (dataResult.FlowResult == FlowResult.FAIL)
                        {
                            return dataResult;
                        }
                        submitData.NextStateCode = dataResult.AppState;
                        if (dataResult.IsCountersign)
                        {
                            #region
                            if (dataResult.FlowResult == FlowResult.Countersign)
                            {
                                if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                                {
                                    return dataResult;
                                }
                            }
                            else
                            {
                                if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                                {
                                    submitData.DictCounterUser = dataResult.DictCounterUser;
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            #region
                            if (dataResult.FlowResult == FlowResult.MULTIUSER)
                            {
                                if (submitData.NextApprovalUser == null || (Utility.GetString(submitData.NextApprovalUser.UserID) == "" || Utility.GetString(submitData.NextApprovalUser.UserName) == ""))
                                {
                                    return dataResult;
                                }
                            }
                            else
                            {
                                if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                                {
                                    submitData.NextApprovalUser = dataResult.UserInfo[0];
                                }
                            }
                            #endregion
                        }

                        #endregion

                        msg += "获取下一状态数据完成" + DateTime.Now.ToString() + "\r\n";


                        msg += "单会签情况" + DateTime.Now.ToString() + "\r\n";
                        #region 对于单会签情况,需要将其他审核人的审核设为会签通过状态

                        if (currentIsCountersign && currentCountersignType == "1")
                        {
                            entity.FLOW_FLOWRECORDMASTER_T.FLOW_FLOWRECORDDETAIL_T
                               .Where(detail => detail.FLOWRECORDDETAILID != entity.FLOWRECORDDETAILID && detail.STATECODE == entity.STATECODE && detail.FLAG == "0")
                               .ToList().ForEach(item =>
                               {
                                   item.FLAG = "1";
                                   item.CHECKSTATE = "7";
                                   UpdateFlowRecord2(con, item);
                               });
                        }
                        #endregion
                        msg += "单会签情况完成" + DateTime.Now.ToString() + "\r\n";

                        #region


                        FlowDataType.FlowData FlowData = new FlowDataType.FlowData();
                        FlowData.xml = submitData.XML;
                        workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                        {
                            instance = null;

                        };
                        msg += "处理kpi" + DateTime.Now.ToString() + "\r\n";

                        #region 处理kpi时间
                        string KPITime = "";
                        //PerformanceServiceWS.PerformanceServiceClient psc = new PerformanceServiceWS.PerformanceServiceClient();
                        string pscResult = entity.FLOW_FLOWRECORDMASTER_T.KPITIMEXML;
                        //psc.Close();
                        if (!string.IsNullOrEmpty(pscResult))
                        {
                            XElement xe = XElement.Parse(pscResult);
                            Func<XElement, bool> f = (x) =>
                            {
                                XAttribute xid = x.Attribute("id");
                                XAttribute xvalue = x.Attribute("value");
                                if (xid == null || xvalue == null)
                                    return false;
                                else
                                {
                                    if (xid.Value == dataResult.AppState)
                                        return true;
                                    else return false;
                                }
                            };
                            XElement FlowNode = xe.Elements("FlowNode").FirstOrDefault(f);
                            if (FlowNode != null)
                            {
                                KPITime = FlowNode.Attribute("value").Value;
                            }
                        }
                        dataResult.KPITime = KPITime;

                        #endregion

                        msg += "处理kpi完成" + DateTime.Now.ToString() + "\r\n";

                        if (!dataResult.IsCountersign)
                        {
                            msg += "非会签" + DateTime.Now.ToString() + "\r\n";
                            #region  非会签

                            UserInfo AppUser = submitData.NextApprovalUser;
                            dataResult.UserInfo.Clear();
                            dataResult.UserInfo.Add(AppUser);
                            UserInfo AgentAppUser = GetAgentUserInfo(submitData.ModelCode, AppUser.UserID);//查询是否启用了代理人                            
                            dataResult = DoFlowRecord2(con, workflowRuntime, instance, entity, submitData.NextStateCode, AppUser, AgentAppUser, submitData.SubmitFlag, submitData.FlowType); //处理流程数据
                            dataResult.AgentUserInfo = AgentAppUser;
                            dataResult.IsCountersign = false;
                            #endregion
                            msg += "非会签完成" + DateTime.Now.ToString() + "\r\n";
                        }
                        else
                        {
                            #region  会签

                            dataResult.DictCounterUser = submitData.DictCounterUser;
                            Dictionary<UserInfo, UserInfo> dictAgentUserInfo = GetAgentUserInfo2(submitData.ModelCode, submitData.DictCounterUser);
                            dataResult = DoFlowRecord_Approval(con, workflowRuntime, instance, entity, submitData.NextStateCode, submitData.DictCounterUser, dictAgentUserInfo, submitData.SubmitFlag, submitData.FlowType); //处理流程数据
                            dataResult.DictAgentUserInfo = dictAgentUserInfo;
                            dataResult.IsCountersign = true;


                            #endregion
                        }

                        msg += "激发流程引擎执行到一下流程" + DateTime.Now.ToString() + "\r\n";
                        #region 激发流程引擎执行到一下流程
                        if (dataResult.AppState == null || dataResult.AppState == "")
                            workflowRuntime.GetService<FlowEvent>().OnDoFlow(instance.InstanceId, FlowData); //激发流程引擎执行到一下流程
                        else
                        {
                            string ss = "";
                            int n = 0;
                            StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(workflowRuntime, instance.InstanceId);

                            workflowinstance.SetState(dataResult.AppState); //流程跳转到指定节点
                            //while (true)
                            //{
                            //    ss += (n++).ToString()+"|" + workflowinstance.CurrentStateName;
                            //    string stateName = workflowinstance.CurrentStateName;

                            //    if (stateName != null && stateName.ToUpper().IndexOf("START") == -1)
                            //    {
                            //        break;
                            //    }
                            //}
                        }
                        #endregion
                        msg += "激发流程引擎执行到一下流程完成" + DateTime.Now.ToString() + "\r\n";
                        //dataResult.CanSendMessage = true;

                        msg += "System.Threading.Thread.Sleep(1000)" + DateTime.Now.ToString() + "\r\n";
                        System.Threading.Thread.Sleep(1000);
                        if (submitData.FlowType == FlowType.Task)
                            dataResult.SubModelCode = Utility.GetSubModelCode(entity.FLOW_FLOWRECORDMASTER_T.ACTIVEROLE, dataResult.AppState); //返回下一子模块代码
                        msg += "System.Threading.Thread.Sleep(1000)完成" + DateTime.Now.ToString() + "\r\n";

                        #endregion
                    }


                }
                dataResult.CurrentIsCountersign = currentIsCountersign;
                dataResult.IsGotoNextState = isGotoNextState;
                return dataResult;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {

                entity = null;
                instance = null;
                SMTWorkFlowManage.ColseWorkFlowRuntime(workflowRuntime);
            }
        }
コード例 #17
0
ファイル: Service2.cs プロジェクト: JuRogn/OA
        /// <summary>
        /// 启动与工作流程相同类型流程,查询对应节点用户
        /// </summary>
        /// <param name="CompanyID">公司ID</param>
        /// <param name="ModelCode">模块代码</param>
        /// <param name="FlowGUID">待审批流GUID,新增时为空或者为StartFlow</param>
        /// <returns></returns>
        public DataResult GetAppUser(OracleConnection con, string CompanyID, string ModelCode, string FlowGUID, string xml)
        {

            DataResult GetAppUserResult = new DataResult();
            try
            {
                string StateName = null;


                if (FlowGUID == "" || FlowGUID == "StartFlow")
                {
                    StateName = "StartFlow";
                }
                else
                {
                    //根据待审批流程GUID,检索待审批状态节点代码
                    List<FLOW_FLOWRECORDDETAIL_T> FlowRecord = FlowBLL2.GetFlowInfo(con, "", FlowGUID, "", "", "", "", "", null);
                    if (FlowRecord == null)
                    {
                        GetAppUserResult.Err = "没有待处理的审核";
                        GetAppUserResult.UserInfo = null;
                        return GetAppUserResult;
                    }
                    StateName = FlowRecord[0].STATECODE;
                }

                //根据公司ID,模块代码获取配置的流程
                WorkflowInstance instance = null;
                LogHelper.WriteLog("根据公司ID,模块代码获取配置的流程FlowBLL2.GetFlowByModelName:OgrType='0'");

                List<FLOW_MODELFLOWRELATION_T> MODELFLOWRELATION = FlowBLL2.GetFlowByModelName(con, CompanyID, "", ModelCode, "0");

                if (MODELFLOWRELATION == null || MODELFLOWRELATION.Count == 0)
                {
                    GetAppUserResult.Err = "没有可使用的流程";
                    GetAppUserResult.UserInfo = null;
                    return GetAppUserResult;
                }
                FLOW_FLOWDEFINE_T Xoml = MODELFLOWRELATION[0].FLOW_FLOWDEFINE_T;

                XmlReader readerxoml, readerule;
                StringReader strXoml = new StringReader(Xoml.XOML);
                StringReader strRules = new StringReader(Xoml.RULES == null ? "" : Xoml.RULES);

                readerxoml = XmlReader.Create(strXoml);
                readerule = XmlReader.Create(strRules);

                WorkflowRuntime workflowRuntime = new WorkflowRuntime();
                workflowRuntime.StartRuntime();

                FlowEvent ExternalEvent = new FlowEvent();
                ExternalDataExchangeService objService = new ExternalDataExchangeService();
                workflowRuntime.AddService(objService);
                objService.AddService(ExternalEvent);
                TypeProvider typeProvider = new TypeProvider(null);
                workflowRuntime.AddService(typeProvider);

                //XmlReader readerxoml = XmlReader.Create(HttpContext.Current.Server.MapPath ("TestFlow.xml"));
                // instance = workflowRuntime.CreateWorkflow(readerxoml);
                if (Xoml.RULES == null)
                    instance = workflowRuntime.CreateWorkflow(readerxoml);
                else
                    instance = workflowRuntime.CreateWorkflow(readerxoml, readerule, null);
                // instance = workflowRuntime.CreateWorkflow(typeof(TestFlow));
                instance.Start();
                StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(workflowRuntime, instance.InstanceId);

                //从实例中获取定义
                if (1 == 2)
                {
                    System.Workflow.Activities.StateMachineWorkflowActivity smworkflow = new StateMachineWorkflowActivity();
                    smworkflow = workflowinstance.StateMachineWorkflow;
                    RuleDefinitions ruleDefinitions = smworkflow.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions;
                    WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer();

                    StringBuilder xoml = new StringBuilder();
                    StringBuilder rule = new StringBuilder();
                    XmlWriter xmlWriter = XmlWriter.Create(xoml);
                    XmlWriter ruleWriter = XmlWriter.Create(rule);
                    markupSerializer.Serialize(xmlWriter, smworkflow);
                    markupSerializer.Serialize(ruleWriter, ruleDefinitions);
                    xmlWriter.Close();
                    ruleWriter.Close();
                    StringReader readxoml = new StringReader(xoml.ToString());
                    StringReader readrule = new StringReader(rule.ToString());
                    XmlReader readerxoml2 = XmlReader.Create(readxoml);
                    XmlReader readerrule2 = XmlReader.Create(readrule);
                    WorkflowInstance instance1 = workflowRuntime.CreateWorkflow(readerxoml2, readerrule2, null);
                    instance1.Start();
                    StateMachineWorkflowInstance workflowinstance1 = new StateMachineWorkflowInstance(workflowRuntime, instance1.InstanceId);
                    workflowinstance1.SetState(StateName);
                }
                //从实例中获取定义并启动新实例

                //跳转到节点StateName
                workflowinstance.SetState(StateName);

                FlowDataType.FlowData FlowData = new FlowDataType.FlowData();
                FlowData.xml = xml;
                //  FlowData.Flow_FlowRecord_T = null;

                ExternalEvent.OnDoFlow(instance.InstanceId, FlowData);//激发流程引擎流转到下一状态
                System.Threading.Thread.Sleep(1000);
                PermissionServiceClient WcfPermissionService = new PermissionServiceClient();
                string CurrentStateName = workflowinstance.CurrentStateName == null ? "End" : workflowinstance.CurrentStateName; //取得当前状态
                List<UserInfo> listUser = new List<UserInfo>();
                if (CurrentStateName != "End")
                {
                    if (CurrentStateName.Substring(0, 5) == "State")
                    {
                        CurrentStateName = CurrentStateName.Substring(5);
                    }
                    string WFCurrentStateName = new Guid(CurrentStateName).ToString("D");
                    T_SYS_USER[]  User = WcfPermissionService.GetSysUserByRole(WFCurrentStateName); //检索本状态(角色)对应用户

                    if (User != null)
                        for (int i = 0; i < User.Length; i++)
                        {
                            UserInfo tmp = new UserInfo();
                            tmp.UserID = User[i].EMPLOYEEID;
                            tmp.UserName = User[i].EMPLOYEENAME;
                            listUser.Add(tmp);
                        }



                }
                else
                {
                    //已经到流程结束状态
                    UserInfo tmp = new UserInfo();
                    tmp.UserID = "End";
                    tmp.UserName = "******";

                    listUser.Add(tmp);
                }


                GetAppUserResult.UserInfo = listUser.Count > 0 ? listUser : null;

                if (GetAppUserResult.UserInfo == null)
                    GetAppUserResult.Err = "没有找到用户";

                return GetAppUserResult;
                // return listUser;


                //return workflowinstance.CurrentStateName == null ? "End" : workflowinstance.CurrentStateName;
            }
            catch (Exception ex)
            {
                GetAppUserResult.Err = ex.Message;
                GetAppUserResult.UserInfo = null;
                return GetAppUserResult;
            }
        }
コード例 #18
0
ファイル: WorkflowMediator.cs プロジェクト: UrviGandhi/IGRSS
        //public static Guid RunWorkflow(Guid instanceId)
        //{
        //    //Check.IsNotTrue(instanceId == Guid.Empty, "Invalid Workflow Instance ID");
        //    InitilizeRuntime();
        //    WorkflowInstance instance = Runtime.GetWorkflow(instanceId);
        //    //Check.IsNotNull(instance, "Could not retrieve workflow");
        //bool result = WorkflowScheduler.RunWorkflow(instance.InstanceId);
        //    //Check.IsTrue(result, "Could not run workflow "
        //    //                    + instance.InstanceId);
        //    return CurrentResultsInContext;
        //}
        public static ReadOnlyCollection<string> GetStateMachineTransitions(Guid instanceID)
        {
            //Check.ArgumentIsNotNull(instanceID, "instanceID");
            InitilizeRuntime();
            ReadOnlyCollection<string> result = null;
            StateMachineWorkflowInstance instance = null;

            try
            {
                instance = new StateMachineWorkflowInstance(Runtime, instanceID);
            }
            catch (InvalidOperationException)
            {
                // the workflow wasnt in the persistence store
                // so we can assume it isn't running
            }

            if (instance != null)
            {
                result = instance.PossibleStateTransitions;
            }
            else
            {
                result = new List<string>().AsReadOnly();
            }

            return result;
        }
コード例 #19
0
ファイル: Mainform.cs プロジェクト: spzenk/sfdocsamples
        private void Runtime_WorkflowIdled(object sender, WorkflowEventArgs e)
        {
            // Get the underlying WorkflowInstance
            StateMachineWorkflowInstance stateMachineInstance = new StateMachineWorkflowInstance(runtime, e.WorkflowInstance.InstanceId);

            // Update the Workflow State & Status on the ListItem 
            this.UpdateListItem(stateMachineInstance.WorkflowInstance,stateMachineInstance.CurrentState.Name, "Running");

            // Update the status of the buttons for the selected ListItem
            this.UpdateUI();
        }
コード例 #20
0
ファイル: FlowBLL.cs プロジェクト: JuRogn/OA
        /// <summary>
        /// 新增流程(对数据库操作)
        /// </summary>
        /// <param name="ApprovalData"></param>
        /// <param name="APPDataResult"></param>
        /// <returns></returns>    
        public DataResult AddFlow2(OracleConnection con, SubmitData submitData, DataResult dataResult, ref FlowUser user)
        {
            // WorkflowRuntime workflowRuntime = null;
            WorkflowInstance instance = null;


            try
            {
                #region 获取定义的流程
                user.TrackingMessage += "获取定义的流程.GetFlowByModelName:submitData.ApprovalUser.DepartmentID=" + submitData.ApprovalUser.DepartmentID + ";OrgType='" + ((int)submitData.FlowType).ToString() + "'";
                List<FLOW_MODELFLOWRELATION_T> MODELFLOWRELATION = GetFlowByModelName(con, submitData.ApprovalUser.CompanyID, submitData.ApprovalUser.DepartmentID, submitData.ModelCode, ((int)submitData.FlowType).ToString(), ref user);//对数据库操作
                if (MODELFLOWRELATION == null || MODELFLOWRELATION.Count == 0)
                {
                    dataResult.FlowResult = FlowResult.FAIL;
                    dataResult.Err = "没有找到可使用的流程";
                    if (submitData.ApprovalUser.CompanyID == user.CompayID && submitData.ApprovalUser.DepartmentID == user.DepartmentID)
                    {
                        dataResult.Err = "没有找到公司[ " + user.CompayName + " ]下部门[ " + user.DepartmentName + " ]的匹配流程返回";
                    }
                    else
                    {
                        dataResult.Err = "没有找到公司[ " + user.CompayName + " ]的可使用匹配流程";

                    }
                    return dataResult;
                }

                #endregion
                FLOW_MODELFLOWRELATION_T flowRelation = MODELFLOWRELATION[0];//只取其中一条流程
                FLOW_FLOWDEFINE_T flowDefine = flowRelation.FLOW_FLOWDEFINE_T;
                user.FlowCode = flowDefine.FLOWCODE;//流程代码
                user.FlowName = flowDefine.DESCRIPTION;//流程名称
                if (flowDefine.RULES != null && flowDefine.RULES.Trim() == "")
                {
                    flowDefine.RULES = null;
                }
                workflowRuntime = SMTWorkFlowManage.CreateWorkFlowRuntime(true);
                instance = SMTWorkFlowManage.CreateWorkflowInstance(workflowRuntime, flowDefine.XOML, flowDefine.RULES);
                LogHelper.WriteLog("新增 FormID=" + user.FormID + " 流程名称=" + flowDefine.DESCRIPTION + "("+flowDefine.FLOWCODE+") 提交人=" + user.UserName + " 公司名称=" + user.CompayName + " 部门名称=" + user.DepartmentName + " 岗位名称=" + user.PostName + "  WorkflowInstance ID=" + instance.InstanceId.ToString());
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                {
                    instance = null;

                };
                #region master赋值
                FLOW_FLOWRECORDMASTER_T master = new FLOW_FLOWRECORDMASTER_T();
                master.INSTANCEID = instance.InstanceId.ToString();
                master.BUSINESSOBJECT = submitData.XML;
                master.FORMID = submitData.FormID;
                master.MODELCODE = submitData.ModelCode;
                master.ACTIVEROLE = Utility.GetActiveRlue(flowDefine.LAYOUT);
                master.FLOWTYPE = ((int)submitData.FlowType).ToString();
                master.FLOWSELECTTYPE = ((int)submitData.FlowSelectType).ToString();
                master.FLOWCODE = flowDefine.FLOWCODE;
                #endregion

                #region 获取下一状态数据
                user.TrackingMessage += "FORMID=" + user.FormID + "获取下一状态数据(开始)";
                GetUserByFlow2(submitData.ApprovalUser.CompanyID, flowDefine.XOML, flowDefine.RULES, master.ACTIVEROLE, submitData.XML, submitData.ApprovalUser.UserID, submitData.ApprovalUser.PostID, submitData.FlowType, ref dataResult, ref user);
                LogHelper.WriteLog("FormID=" + user.FormID + " 获取下一状态数据! dataResult.FlowResult=" + dataResult.FlowResult.ToString());
                user.TrackingMessage += "FORMID=" + user.FormID + "获取下一状态数据(结束)";
                if (dataResult.FlowResult == FlowResult.FAIL)
                {
                    return dataResult;
                }
                submitData.NextStateCode = dataResult.AppState;
                if (dataResult.IsCountersign)
                {
                    #region 检查会签是角色是否有审核人员
                    #region 记录日志
                    if(submitData.DictCounterUser!=null)
                    {
                         LogHelper.WriteLog("FormID=" + user.FormID + " submitData.DictCounterUser="******"FormID=" + user.FormID + "  dataResult.DictCounterUser="******"FormID=" + user.FormID + " submitData.DictCounterUser 会签角色里没有发现有审核人员,所以返回!");
                            return dataResult;
                        }
                    }
                    else
                    {
                        if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                        {
                            submitData.DictCounterUser = dataResult.DictCounterUser;
                        }
                    }
                    #endregion
                }
                else
                {
                    #region 检查非会签角色里是否有审核人员
                    if (dataResult.FlowResult == FlowResult.MULTIUSER)
                    {
                        LogHelper.WriteLog("FormID=" + user.FormID + " 发现有多个审核人员!");
                        if (submitData.NextApprovalUser == null || (Utility.GetString(submitData.NextApprovalUser.UserID) == "" || Utility.GetString(submitData.NextApprovalUser.UserName) == ""))
                        {
                            LogHelper.WriteLog("FormID=" + user.FormID + " 发现有多个审核人员!但下一审核人为空,所以返回选择审核人!");
                            return dataResult;
                        }
                        else
                        {
                            LogHelper.WriteLog("FormID=" + user.FormID + " 发现有多个审核人员,但发现下一审核人不为空 usrid="+(Utility.GetString(submitData.NextApprovalUser.UserID)+" 姓名="+Utility.GetString(submitData.NextApprovalUser.UserName)));
                        }
                    }
                    else
                    {
                        if (submitData.DictCounterUser == null || submitData.DictCounterUser.Keys.Count == 0)
                        {
                            submitData.NextApprovalUser = dataResult.UserInfo[0];
                        }
                    }
                    #endregion
                }

                #endregion

                #region 实体赋值 当提交人为空时,创建人变成单据所属人,如果不为空,则创建人保存为系统登录人;创建公司,部门,岗位,仍然保存单据所属人的公司,部门,岗位
                FLOW_FLOWRECORDDETAIL_T entity = new FLOW_FLOWRECORDDETAIL_T();
                entity.FLOW_FLOWRECORDMASTER_T = master;
                entity.CREATECOMPANYID = submitData.ApprovalUser.CompanyID;
                entity.CREATEDEPARTMENTID = submitData.ApprovalUser.DepartmentID ;
                entity.CREATEPOSTID = submitData.ApprovalUser.PostID;
                entity.CREATEUSERID = string.IsNullOrEmpty(submitData.SumbitUserID) ? submitData.ApprovalUser.UserID : submitData.SumbitUserID;
                entity.CREATEUSERNAME = string.IsNullOrEmpty(submitData.SumbitUserName) ? submitData.ApprovalUser.UserName : submitData.SumbitUserName;
                #endregion
                user.TrackingMessage += " 处理kpi时间\r\n";
                #region 处理kpi时间
                string KPITime = "";
                #region 加入缓存
                string pscResult = CacheProvider.GetCache<string>(flowRelation.MODELFLOWRELATIONID);
                if (string.IsNullOrEmpty(pscResult))
                {
                    PerformanceServiceWS.PerformanceServiceClient psc = new PerformanceServiceWS.PerformanceServiceClient();
                    pscResult = psc.GetKPIPointsByBusinessCode(flowRelation.MODELFLOWRELATIONID);//调用服务
                    CacheProvider.Add<string>(flowRelation.MODELFLOWRELATIONID, pscResult);
                    psc.Close();
                }
                #endregion
                //PerformanceServiceWS.PerformanceServiceClient psc = new PerformanceServiceWS.PerformanceServiceClient();
                //string pscResult = psc.GetKPIPointsByBusinessCode(flowRelation.MODELFLOWRELATIONID);//调用服务
                //psc.Close();
                if (!string.IsNullOrEmpty(pscResult))
                {
                    XElement xe = XElement.Parse(pscResult);
                    Func<XElement, bool> f = (x) =>
                    {
                        XAttribute xid = x.Attribute("id");
                        XAttribute xvalue = x.Attribute("value");
                        if (xid == null || xvalue == null)
                            return false;
                        else
                        {
                            if (xid.Value == dataResult.AppState)
                                return true;
                            else return false;
                        }
                    };
                    XElement FlowNode = xe.Elements("FlowNode").FirstOrDefault(f);
                    if (FlowNode != null)
                    {
                        KPITime = FlowNode.Attribute("value").Value;
                    }
                }

                dataResult.KPITime = KPITime;
                master.KPITIMEXML = pscResult;
                #endregion
                user.TrackingMessage += " 处理kpi时间完成\r\n";
                FlowDataType.FlowData FlowData = new FlowDataType.FlowData();
                FlowData.xml = submitData.XML;

                if (!dataResult.IsCountersign)
                {
                    #region  确定非会签的下一个审核人
                    UserInfo AppUser = new UserInfo(); //下一审核人
                    AppUser = submitData.NextApprovalUser;
                    dataResult.UserInfo.Clear();
                    dataResult.UserInfo.Add(AppUser);
                    UserInfo AgentAppUser = GetAgentUserInfo(submitData.ModelCode, AppUser.UserID);//查询是否启用了代理人                    
                    dataResult = DoFlowRecord2(con, workflowRuntime, instance, entity, submitData.NextStateCode, AppUser, AgentAppUser, submitData.SubmitFlag, submitData.FlowType,ref user); //处理流程数据
                    dataResult.IsCountersign = false;
                    dataResult.AgentUserInfo = AgentAppUser;
                    #endregion
                }
                else
                {
                    user.TrackingMessage += " 会签\r\n";
                    #region  确定会签角色里的审核人员
                    //Tracer.Debug("-----DoFlowRecord_Add:" + DateTime.Now.ToString()+"\n");
                    dataResult.DictCounterUser = submitData.DictCounterUser;
                    Dictionary<UserInfo, UserInfo> dictAgentUserInfo = GetAgentUserInfo2(submitData.ModelCode, submitData.DictCounterUser);
                    dataResult = DoFlowRecord_Add(con, workflowRuntime, instance, entity, submitData.NextStateCode, submitData.DictCounterUser, dictAgentUserInfo, submitData.SubmitFlag, submitData.FlowType); //处理流程数据
                    //Tracer.Debug("-----DoFlowRecord_AddEnd:" + DateTime.Now.ToString()+"\n");
                    dataResult.IsCountersign = true;
                    dataResult.DictAgentUserInfo = dictAgentUserInfo;
                    #endregion
                    user.TrackingMessage += "会签完成\r\n";
                }
                user.TrackingMessage += "激发流程引擎执行到一下流程\r\n";
                #region 激发流程引擎执行到一下流程
                string ss = "";
                int n = 0;
                StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(workflowRuntime, instance.InstanceId);
                ManualWorkflowSchedulerService scheduleService = workflowRuntime.GetService(typeof(ManualWorkflowSchedulerService)) as ManualWorkflowSchedulerService;
               if (dataResult.AppState == null || dataResult.AppState == "")
                {
                    user.TrackingMessage += " workflowRuntime.GetService<FlowEvent>()\r\n";
                    scheduleService.RunWorkflow(workflowinstance.InstanceId);
                    workflowRuntime.GetService<FlowEvent>().OnDoFlow(instance.InstanceId, FlowData); //激发流程引擎执行到一下流程
                    scheduleService.RunWorkflow(workflowinstance.InstanceId);
                    user.TrackingMessage += " workflowRuntime.GetService<FlowEvent>()完成\r\n";
                }
                else
                {
                    scheduleService.RunWorkflow(workflowinstance.InstanceId);
                    workflowinstance.SetState(dataResult.AppState); //流程跳转到指定节点
                }

                #endregion
                user.TrackingMessage += "激发流程引擎执行到一下流程完成\r\n";
                user.TrackingMessage += "System.Threading.Thread.Sleep(1000)\r\n";
                //System.Threading.Thread.Sleep(1000);//当前用到
                dataResult.ModelFlowRelationID = flowRelation.MODELFLOWRELATIONID; //返回关联ID
                dataResult.KPITime = KPITime;
                //dataResult.CanSendMessage = true;
                if (submitData.FlowType == FlowType.Task)
                {
                    dataResult.SubModelCode = Utility.GetSubModelCode(master.ACTIVEROLE, dataResult.AppState); //返回下一子模块代码
                }
                user.TrackingMessage += "System.Threading.Thread.Sleep(1000)完成\r\n";
                return dataResult;
            }

            catch (Exception e)
            {
                user.ErrorMsg += "新增流程出错 FormID=" + user.FormID + " CompayName=" + user.CompayName + "FlowName=" + user.FlowName + "异常信息:\r\n" + e.ToString() + "\r\n";
                LogHelper.WriteLog("FormID=" + user.FormID + " CompayName=" + user.CompayName + "FlowName=" + user.FlowName + " 新增流程出错,异常信息:\r\n" + e.ToString());
                throw new Exception("FormID=" + user.FormID+" 时间:"+DateTime.Now.ToString()+" 新增流程出错,请联系管理员! ");
            }
            finally
            {
                instance = null;
                SMTWorkFlowManage.ColseWorkFlowRuntime(workflowRuntime);
            }


        }