예제 #1
0
        private static SqlWorkflowInstanceStore CreateInstanceStore(WorkflowHandlerBase workflowInstance, out InstanceHandle ownerHandle)
        {
            try
            {
                //WriteDebug("CreateInstanceStore: " + workflowInstance.WorkflowInstanceGuid + ", nodeId: " + workflowInstance.Id);

                var store = new SqlWorkflowInstanceStore(ConnectionString);
                ownerHandle = store.CreateInstanceHandle();

                var wfHostTypeName = GetWorkflowHostTypeName(workflowInstance);
                var WorkflowHostTypePropertyName = GetWorkflowHostTypePropertyName();

                var ownerCommand = new CreateWorkflowOwnerCommand()
                {
                    InstanceOwnerMetadata = { { WorkflowHostTypePropertyName, new InstanceValue(wfHostTypeName) } }
                };
                var owner = store.Execute(ownerHandle, ownerCommand, TimeSpan.FromSeconds(30)).InstanceOwner;
                ownerHandle.Free();
                store.DefaultInstanceOwner = owner;
                return(store);
            }
            catch (Exception e)
            {
                WriteError("CreateInstanceStore", e);
                throw;
            }
        }
        internal static InstanceStore InitializeWorkflowInstanceStore()
        {
            //return new XmlWorkflowInstanceStore();

            string connectionString = ConfigurationManager.ConnectionStrings["wf"].ConnectionString;
            var    store            = new SqlWorkflowInstanceStore(connectionString);

            //TODO: выставить после отладки
            //store.InstanceEncodingOption = InstanceEncodingOption.GZip;

            // про настройки тут: https://msdn.microsoft.com/ru-ru/library/ee395770(v=vs.110).aspx
            store.InstanceLockedExceptionAction    = InstanceLockedExceptionAction.AggressiveRetry;
            store.InstanceCompletionAction         = InstanceCompletionAction.DeleteAll;
            store.HostLockRenewalPeriod            = new TimeSpan(0, 0, 5);
            store.RunnableInstancesDetectionPeriod = new TimeSpan(0, 0, 10);

            InstanceHandle handle = null;

            try
            {
                handle = store.CreateInstanceHandle();
                var view = store.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(5));
                store.DefaultInstanceOwner = view.InstanceOwner;
            }
            finally
            {
                if (handle != null)
                {
                    handle.Free();
                }
            }
            return(store);
        }
예제 #3
0
    //end

    protected void btnEdit_ServerClick(object sender, EventArgs e)
    {
        if (((this.txtName.Value.Length == 0) || (this.uploadurl.Value.Length == 0)) || (this.selWorkFlow.SelectedValue.Length == 0))
        {
            MessageBox.Show(this, "请您填写完整的信息");
        }
        else
        {
            Model.SelectRecord selectRecord = new Model.SelectRecord("WorkFlow", "", "*", "where id='" + this.selWorkFlow.SelectedValue + "'");
            DataTable          table        = BLL.SelectRecord.SelectRecordData(selectRecord).Tables[0];
            string             content      = File.ReadAllText(System.Web.HttpContext.Current.Request.MapPath("../") + table.Rows[0]["URL"].ToString());

            //ziyunhx add 2013-8-5 workflow Persistence
            //old code
            //WorkFlowTracking.instance = engineManager.createInstance(content, null, null);
            //WorkFlowTracking.instance.Run();
            //new code
            instance = engineManager.createInstance(content, null, null);
            if (instanceStore == null)
            {
                instanceStore = new SqlWorkflowInstanceStore(SqlHelper.strconn);
                view          = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
                instanceStore.DefaultInstanceOwner = view.InstanceOwner;
            }
            instance.InstanceStore = instanceStore;
            instance.Run();
            //end

            Model.Document documents = new Model.Document
            {
                ID     = id.Trim(),
                Name   = this.txtName.Value.Trim(),
                URL    = this.uploadurl.Value.Trim(),
                Remark = this.txtReMark.Value.Trim(),
                WID    = this.selWorkFlow.SelectedValue,
                WStep  = "0",
                Result = "0",
                UID    = this.Session["admin"].ToString(),
                //ziyunhx add 2013-8-5 workflow Persistence
                //old code
                //FlowInstranceID = WorkFlowTracking.instance.Id,
                //new code
                FlowInstranceID = instance.Id,
                //end
            };

            if (BLL.Document.DocumentUpdate(documents) == 1)
            {
                UserOperatingManager.InputUserOperating(this.Session["admin"].ToString(), "工作流管理", "编辑工作流" + documents.Name + "的信息成功");
                MessageBox.ShowAndRedirect(this, "编辑公文成功!", "/document/DocumentList.aspx");
            }
            else
            {
                UserOperatingManager.InputUserOperating(this.Session["admin"].ToString(), "工作流管理", "编辑工作流" + documents.Name + "的信息失败");
                MessageBox.Show(this, "编辑工作流失败");
            }
        }
    }
예제 #4
0
//<Snippet1>
        static void SetupInstanceStore()
        {
            instanceStore =
                new SqlWorkflowInstanceStore(@"Data Source=.\SQLEXPRESS;Initial Catalog=SampleInstanceStore;Integrated Security=True;Asynchronous Processing=True");
            InstanceHandle handle = instanceStore.CreateInstanceHandle();
            InstanceView   view   = instanceStore.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));

            handle.Free();
            instanceStore.DefaultInstanceOwner = view.InstanceOwner;
        }
예제 #5
0
        private static InstanceStore CreateInstanceStore(out InstanceHandle handle)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["WorkflowDb"].ConnectionString;
            var store            = new SqlWorkflowInstanceStore(connectionString);

            handle = store.CreateInstanceHandle();

            store.DefaultInstanceOwner = CreateWorkflowInstanceOwner(store, handle);

            return(store);
        }
예제 #6
0
        /// <summary>
        /// 获取工作流持久化的实例
        /// </summary>
        /// <returns></returns>
        private InstanceStore GetInstanceStore()
        {
            InstanceStore instanceStore = new SqlWorkflowInstanceStore(m_ConnectionString);
            InstanceView  view          = instanceStore.Execute
                                              (instanceStore.CreateInstanceHandle(),
                                              new CreateWorkflowOwnerCommand(),
                                              TimeSpan.FromSeconds(30));

            instanceStore.DefaultInstanceOwner = view.InstanceOwner;
            return(instanceStore);
        }
예제 #7
0
        public static System.Runtime.DurableInstancing.InstanceStore NewStore(TimeSpan timeout)
        {
            var store = new SqlWorkflowInstanceStore("Server =localhost; Initial Catalog = WF; Integrated Security = SSPI")
            {
            };

            var handle = store.CreateInstanceHandle();
            var view   = store.Execute(handle, new CreateWorkflowOwnerCommand(), timeout);

            handle.Free();
            store.DefaultInstanceOwner = view.InstanceOwner;
            return(store);
        }
예제 #8
0
 private static void DeleteInstanceStoreOwner()
 {
     try
     {
         InstanceHandle handle = instanceStore.CreateInstanceHandle();
         InstanceView   view   = instanceStore.Execute(handle, new DeleteWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
         handle.Free();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #9
0
        public WorkflowInstance LoadWorkflow(Guid instanceId)
        {
            var instance = this._repository.LoadWorkflowInstance(instanceId);
            var activity = Helpers.LoadWorkflowActiovityFromXaml(this._workflowRepositoryPath + instance.WorkflowName, this._errorLogger);

            if (activity != null)
            {
                WorkflowApplication app = new WorkflowApplication(activity);
                app.Extensions.Add(() =>
                {
                    SQLTrackingPaticipant participant = new SQLTrackingPaticipant();
                    participant.ConnectionString      = _connectionString;
                    participant.TrackingProfile       = CreateTrackingProfile();
                    return(participant);
                });
                if (this._isPersistable)
                {
                    //setup persistence
                    InstanceStore store = new SqlWorkflowInstanceStore(
                        this._connectionString);
                    InstanceHandle handle = store.CreateInstanceHandle();
                    InstanceView   view   = store.Execute(handle,
                                                          new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
                    handle.Free();
                    store.DefaultInstanceOwner = view.InstanceOwner;
                    app.InstanceStore          = store;
                    app.PersistableIdle        = (e) => { return(PersistableIdleAction.Persist); };
                }
                try
                {
                    app.Load(instanceId);
                    app.Run();

                    instance.SetApplicationhost(app);
                    instance.SetWorkflowInstanceHandeler(this);

                    instance.State      = InstanceState.Loaded;
                    instance.InstanceId = instanceId;
                    this._managedWorkflows.Add(instance);
                    this._repository.UpdateWorkflowInstanceState(app.Id, InstanceState.Loaded, instance.Bookmarks.ConvertStringListToCommaSeparatedString());

                    return(instance);
                }
                catch (Exception ex)
                {
                    this._errorLogger.Log(ex.Message, LoggerInfoTypes.Error);
                }
            }
            return(null);
        }
예제 #10
0
        private static InstanceStore CreateInstanceStore()
        {
            string connectionString = ConfigurationManager.ConnectionStrings
                                      ["InstanceStore"].ConnectionString;
            InstanceStore store =
                new SqlWorkflowInstanceStore(connectionString);
            InstanceView view = store.Execute(
                store.CreateInstanceHandle(),
                new CreateWorkflowOwnerCommand(),
                TimeSpan.FromSeconds(30));

            store.DefaultInstanceOwner = view.InstanceOwner;
            return(store);
        }
예제 #11
0
        public void ResumeWorkFlow(BusinessObject.DtoModels.Game game)
        {
            Exception exception = new Exception();

            Guid workflowInstanceID = game.InstanceId;

            SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(databaseConnection);

            store.InstanceLockedExceptionAction = InstanceLockedExceptionAction.BasicRetry;
            store.HostLockRenewalPeriod         = TimeSpan.FromSeconds(2);


            InstanceHandle             instanceHandle = store.CreateInstanceHandle();
            CreateWorkflowOwnerCommand createOwnerCmd = new CreateWorkflowOwnerCommand();
            InstanceView view = store.Execute(instanceHandle, createOwnerCmd, TimeSpan.FromSeconds(10));

            store.DefaultInstanceOwner = view.InstanceOwner;

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

            AutoResetEvent syncEvent = new AutoResetEvent(false);

            WorkflowApplication wfApplication = new WorkflowApplication(new FlowchartNumberGuessWorkflow(), instance.DefinitionIdentity);

            wfApplication.PersistableIdle      = (e) => PersistableIdleAction.Unload;
            wfApplication.Unloaded             = (e) => { syncEvent.Set(); };
            wfApplication.OnUnhandledException = (e) =>
            {
                exception = e.UnhandledException;
                syncEvent.Set();
                return(UnhandledExceptionAction.Cancel);
            };

            wfApplication.Load(instance);

            BookmarkResumptionResult result = wfApplication.ResumeBookmark("Decision", game);

            syncEvent.WaitOne();

            if (exception.Message != string.Empty && exception.StackTrace != null)
            {
                throw exception;
            }

            DeleteWorkflowOwnerCommand deleteOwnerCmd = new DeleteWorkflowOwnerCommand();

            store.Execute(instanceHandle, deleteOwnerCmd, TimeSpan.FromSeconds(10));
        }
        public WFDefinitionIdentityFactory()
        {
            InstanceDefinitions = new System.Collections.Concurrent.ConcurrentDictionary <WorkflowIdentity, Activity>();

            Store = new SqlWorkflowInstanceStore("Server =localhost; Initial Catalog = WF; Integrated Security = SSPI")
            {
                InstanceCompletionAction = InstanceCompletionAction.DeleteAll,
                InstanceEncodingOption   = InstanceEncodingOption.GZip,
            };

            var handle = Store.CreateInstanceHandle();
            var view   = Store.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(50));

            handle.Free();
            Store.DefaultInstanceOwner = view.InstanceOwner;
        }
예제 #13
0
        public WorkflowApplicationInstance GetInstance(Guid workflowInstanceID)
        {
            SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(databaseConnection);

            store.InstanceLockedExceptionAction = InstanceLockedExceptionAction.BasicRetry;
            store.HostLockRenewalPeriod         = TimeSpan.FromSeconds(2);


            InstanceHandle             instanceHandle = store.CreateInstanceHandle();
            CreateWorkflowOwnerCommand createOwnerCmd = new CreateWorkflowOwnerCommand();
            InstanceView view = store.Execute(instanceHandle, createOwnerCmd, TimeSpan.FromSeconds(10));

            store.DefaultInstanceOwner = view.InstanceOwner;

            return(WorkflowApplication.GetInstance(workflowInstanceID, store));
        }
예제 #14
0
        private static SqlWorkflowInstanceStore CreateInstanceStore(WorkflowHandlerBase workflowInstance)
        {
            var store       = new SqlWorkflowInstanceStore(ConnectionString);
            var ownerHandle = store.CreateInstanceHandle();

            var wfHostTypeName = GetWorkflowHostTypeName(workflowInstance);
            var WorkflowHostTypePropertyName = GetWorkflowHostTypePropertyName();

            var ownerCommand =
                new CreateWorkflowOwnerCommand()
            {
                InstanceOwnerMetadata = { { WorkflowHostTypePropertyName, new InstanceValue(wfHostTypeName) } }
            };

            store.DefaultInstanceOwner = store.Execute(ownerHandle, ownerCommand, TimeSpan.FromSeconds(30)).InstanceOwner;
            return(store);
        }
예제 #15
0
        public void InitWorkflowApplication()
        {
            instanceStore = new SqlWorkflowInstanceStore(connStr);
            view          = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
            instanceStore.DefaultInstanceOwner = view.InstanceOwner;
            instance.InstanceStore             = instanceStore;

            instance.Idle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                idleEvent.Set();
            };

            instance.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                idleEvent.Set();
            };
        }
예제 #16
0
        public static InstanceStore SetupInstanceStore()
        {
            //***********Important Notice*************
            //You need to modify the following line of code before running the sample.
            //Replace the value of myConnectionString with the value of the "Connection String" property
            //of the WorkflowInstanceStore database on your own machine.
            string        myConnectionString = @"Data Source=localhost;Initial Catalog=PersistenceDB;Integrated Security=True";
            InstanceStore instanceStore      = new SqlWorkflowInstanceStore(myConnectionString);

            InstanceHandle handle = instanceStore.CreateInstanceHandle();
            InstanceView   view   = instanceStore.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));

            handle.Free();

            instanceStore.DefaultInstanceOwner = view.InstanceOwner;

            return(instanceStore);
        }
예제 #17
0
        private SqlWorkflowInstanceStore SetupInstanceStore()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["InstanceStore"].ConnectionString;

            var result = new SqlWorkflowInstanceStore(connectionString);

            result.InstanceCompletionAction      = InstanceCompletionAction.DeleteAll;
            result.InstanceEncodingOption        = InstanceEncodingOption.None;
            result.InstanceLockedExceptionAction = InstanceLockedExceptionAction.AggressiveRetry;

            var handle = result.CreateInstanceHandle();
            var view   = result.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));

            result.DefaultInstanceOwner = view.InstanceOwner;
            handle.Free();

            return(result);
        }
예제 #18
0
        public Guid NewWorkFlow(string workflowName, IDictionary <string, object> parameters)
        {
            var activity = Helpers.LoadWorkflowActiovityFromXaml(this._workflowRepositoryPath + workflowName, this._errorLogger);

            if (activity != null)
            {
                WorkflowApplication app = new WorkflowApplication(activity, parameters);
                app.Extensions.Add(() =>
                {
                    SQLTrackingPaticipant participant = new SQLTrackingPaticipant();
                    participant.ConnectionString      = _connectionString;
                    return(participant);
                });

                if (this._isPersistable)
                {
                    //setup persistence
                    InstanceStore store = new SqlWorkflowInstanceStore(
                        this._connectionString);
                    InstanceHandle handle = store.CreateInstanceHandle();
                    InstanceView   view   = store.Execute(handle,
                                                          new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
                    handle.Free();
                    store.DefaultInstanceOwner = view.InstanceOwner;
                    app.InstanceStore          = store;
                    app.PersistableIdle        = (e) => { return(PersistableIdleAction.Unload); };
                }
                try
                {
                    app.Run();
                    var wfinstance = new WorkflowInstance(workflowName, this, app);
                    wfinstance.State      = InstanceState.Created;
                    wfinstance.InstanceId = app.Id;
                    this._managedWorkflows.Add(wfinstance);
                    this._repository.SaveWorkflowInstanceState(app.Id, workflowName, InstanceState.Created, string.Empty);
                    return(app.Id);
                }
                catch (Exception ex)
                {
                    this._errorLogger.Log(ex.Message, LoggerInfoTypes.Error);
                }
            }
            return(Guid.Empty);
        }
예제 #19
0
        private static void SetupInstanceStore()
        {
            try
            {
                instanceStore =
                    new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["WFConnection"].ToString());
                instanceStore.InstanceCompletionAction = InstanceCompletionAction.DeleteNothing;

                InstanceHandle handle = instanceStore.CreateInstanceHandle();
                InstanceView   view   = instanceStore.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
                handle.Free();

                instanceStore.DefaultInstanceOwner = view.InstanceOwner;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #20
0
        public string Load(string id, string bookMark, params object[] ids)
        {
            _connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
            _instanceStore    = new SqlWorkflowInstanceStore(_connectionString);
            InstanceView view = _instanceStore.Execute
                                    (_instanceStore.CreateInstanceHandle(),
                                    new CreateWorkflowOwnerCommand(),
                                    TimeSpan.FromSeconds(30));

            _instanceStore.DefaultInstanceOwner = view.InstanceOwner;
            WorkflowApplication i = new WorkflowApplication(ActivityXamlServices.Load(""));

            i.InstanceStore   = _instanceStore;
            i.PersistableIdle = (waiea) => PersistableIdleAction.Unload;
            i.Load(new Guid(id));

            var dd = i.ResumeBookmark(bookMark, ids);

            //var b = i.GetBookmarks();
            return("ok");
        }
예제 #21
0
        private static InstanceStore CreateInstanceStore()
        {
            var conn  = ConfigurationManager.ConnectionStrings["ApacheConnection"].ConnectionString;
            var store = new SqlWorkflowInstanceStore(conn)
            {
                InstanceLockedExceptionAction    = InstanceLockedExceptionAction.AggressiveRetry,
                InstanceCompletionAction         = InstanceCompletionAction.DeleteNothing,
                HostLockRenewalPeriod            = TimeSpan.FromSeconds(20),
                RunnableInstancesDetectionPeriod = TimeSpan.FromSeconds(3)
            };

            StateMachineStateTracker.Promote(store);
            var handle = store.CreateInstanceHandle();
            var view   = store.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(60));

            store.DefaultInstanceOwner = view.InstanceOwner;

            handle.Free();

            return(store);
        }
        /// <summary>
        /// 创建并启动一个工作流,在申请时候触发
        /// </summary>
        /// <param name="meeting">申请时所填表单的数据</param>
        /// <returns>返回一个Guid</returns>
        public static Guid CreateAndRun(Model.Meeting meeting, Dictionary <int, int> d_EquipmentCount, Dictionary <string, string> MeetingUserNameAndEmail, Model.MeetingRoom MeetingRoomIDAndName)
        {
            SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(connectionString);
            InstanceView             view          = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromDays(30));

            instanceStore.DefaultInstanceOwner = view.InstanceOwner;

            IDictionary <string, object> input = new Dictionary <string, object>();

            input.Add("Request", meeting);
            input.Add("EquipmentCount", d_EquipmentCount);
            input.Add("MeetingUserEmailFrom", MeetingUserNameAndEmail);
            input.Add("MeetingRoomIDAndName", MeetingRoomIDAndName);
            WorkflowApplication application = new WorkflowApplication(new MeetingApply(), input);

            application.InstanceStore   = instanceStore;
            application.PersistableIdle = (e) =>
            {
                instanceUnloaded.Set();
                return(PersistableIdleAction.Unload);
            };

            application.Unloaded = (e) =>
            {
                instanceUnloaded.Set();
            };

            application.OnUnhandledException = (ex) =>
            {
                return(UnhandledExceptionAction.Terminate);
            };

            Guid id = application.Id;

            application.Persist();
            application.Run();
            instanceUnloaded.WaitOne();
            return(id);
        }
예제 #23
0
        SqlWorkflowInstanceStore CreateInstanceStore(String cnnString)
        {
            String cnnStr = cnnString;

            if (cnnStr.IndexOf("Asynchronous Processing") == -1)
            {
                cnnStr += ";Asynchronous Processing=True";
            }
            var _store = new SqlWorkflowInstanceStore(cnnStr)
            {
                InstanceLockedExceptionAction    = InstanceLockedExceptionAction.AggressiveRetry,
                HostLockRenewalPeriod            = _wfTimeSpan,
                RunnableInstancesDetectionPeriod = TimeSpan.FromSeconds(RUNNABLE_INSTANCES_DETECTION_PERIOD),
                InstanceCompletionAction         = InstanceCompletionAction.DeleteNothing
            };
            InstanceHandle handle = _store.CreateInstanceHandle();
            InstanceView   view   = _store.Execute(handle, new CreateWorkflowOwnerCommand(), _wfTimeSpan);

            _store.DefaultInstanceOwner = view.InstanceOwner;
            handle.Free();
            return(_store);
        }
예제 #24
0
        public static Guid CreateAndRun(RequestForm requsetForm)
        {
            //工作流服务实例的状态信息持久保存到数据库中
            //SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore("server=.;database=aspnetdb;uid=sa;pwd=0000");
            SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(@"Data Source=.\SQLEXPRESS;Initial Catalog=aspnetdb;Integrated Security=True");//在宿主程序中首先我们创建SqlWorkflowInstanceStore的实例
            InstanceView             view          = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));

            instanceStore.DefaultInstanceOwner = view.InstanceOwner;//对SqlWorkflowInstanceStore实例的各种配置

            IDictionary <string, object> input = new Dictionary <string, object>
            {
                { "Request", requsetForm }
            };

            WorkflowApplication application = new WorkflowApplication(new UseCarApply(), input);

            application.InstanceStore   = instanceStore; //并将application的InstanceStore属性设置为该实例来指定使用的持久化存储
            application.PersistableIdle = (e) =>         //获取工作流实例处于空闲状态并且可被保留时调用
            {
                instanceUnloaded.Set();
                return(PersistableIdleAction.Unload);  //保持并且卸载工作流
            };
            application.Unloaded = (e) =>              //获取或设置卸载当前工作流时调用
            {
                instanceUnloaded.Set();                //将事件设置为主终止状态允许其他的线程继续。
            };
            application.OnUnhandledException = (ex) => //异常
            {
                Console.Write("Exception");
                return(UnhandledExceptionAction.Terminate);
            };

            Guid id = application.Id;

            //application.Persist();
            application.Run();
            instanceUnloaded.WaitOne();//阻止当前线程,直到收到信号
            return(id);
        }
예제 #25
0
        private static void DurableDelayTest()
        {
            string connectionString = ConfigurationManager.ConnectionStrings
                                      ["InstanceStore"].ConnectionString;
            InstanceStore store =
                new SqlWorkflowInstanceStore(connectionString);
            InstanceView view = store.Execute(
                store.CreateInstanceHandle(),
                new CreateWorkflowOwnerCommand(),
                TimeSpan.FromSeconds(30));

            store.DefaultInstanceOwner = view.InstanceOwner;

            ManualResetEvent completedWaitEvent = new ManualResetEvent(false);

            WorkflowApplication wfApp = new WorkflowApplication(new Workflow1());

            wfApp.InstanceStore = store;

            wfApp.Completed = (e) =>
            {
                Console.WriteLine("Completed");
                completedWaitEvent.Set();
            };
            wfApp.Idle = (e) =>
            {
                Console.WriteLine("Idle");
            };

            wfApp.PersistableIdle = (e) =>
            {
                Console.WriteLine("PersistableIdle");
                return(PersistableIdleAction.Unload);
            };

            wfApp.Run();
            completedWaitEvent.WaitOne(5000);
        }
예제 #26
0
        private static SqlWorkflowInstanceStore CreateInstanceStore(System.Activities.Activity workflow, out InstanceHandle ownerHandle)
        {
            try
            {
                var store = new SqlWorkflowInstanceStore(ConnectionString);
                ownerHandle = store.CreateInstanceHandle();

                var wfHostTypeName = GetWorkflowHostTypeName(workflow);
                var WorkflowHostTypePropertyName = GetWorkflowHostTypePropertyName();

                var ownerCommand = new CreateWorkflowOwnerCommand()
                {
                    InstanceOwnerMetadata = { { WorkflowHostTypePropertyName, new InstanceValue(wfHostTypeName) } }
                };
                var owner = store.Execute(ownerHandle, ownerCommand, TimeSpan.FromSeconds(30)).InstanceOwner;
                ownerHandle.Free();
                store.DefaultInstanceOwner = owner;
                return(store);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #27
0
        public void ResetWorkflow(int workflowID, int workflowInstanceID, int userID, List <string> exchangeParamLists)
        {
            Dictionary <string, object> exchangeParams = new Dictionary <string, object>();
            Dictionary <string, object> workflowParams = new Dictionary <string, object>();

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

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

            DynEntity workflowInstance = null;

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

                workflowApplication = new WorkflowApplication(activity);

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

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

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

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

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

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

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

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

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

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

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

                    workflowApplication.InstanceStore        = instanceStore;
                    workflowApplication.PersistableIdle      = workflowPersistableIdle;
                    workflowApplication.Idle                 = workflowIdle;
                    workflowApplication.Unloaded             = unload;
                    workflowApplication.Aborted              = workflowAborted;
                    workflowApplication.Completed            = workflowCompleted;
                    workflowApplication.OnUnhandledException = workflowUnhandledException;
                    workflowApplication.Run();
                    trans.Complete();
                }
            }
            else
            {
                throw new ApplicationException("数据库中工作流实例不存在,请检查!");
            }
        }
예제 #28
0
        /// <summary>
        ///     Starts processing the given activity via the WorkflowApplication.
        /// </summary>
        /// <param name="command">The command to be ran.</param>
        /// <param name="firstParameter">The first parameter to include (if any).</param>
        /// <param name="secondParameter">The second parameter to include (if any).</param>
        /// <param name="thirdParameter">The third parameter to include (if any).</param>
        private void StartWorkflowScience(string command, string firstParameter, string secondParameter, string thirdParameter /* future use */)
        {
            // Now stage the WorkflowApplication, using the SQL instance, wrapped in using to dispose all of the things when done.
            using (AutoResetEvent syncEvent = new AutoResetEvent(false))
            {
                // NOTE: If the string doesn't - explicitly - match, the .ctor() of the
                // SwedishCodeActivity will throw, since the string is the key. Also,
                // no boxing/unboxing required for Dictionary<T,T>; which saves overhead.
                Dictionary <string, SwedishCodeActivity <object> > newDictionary = new Dictionary <string, SwedishCodeActivity <object> >
                {
                    // See the 'Activities' folder for examples of Activities that you can use here.
                    { "CheckFreeDiskSpaceActivity", new CheckFreeDiskSpaceActivity() },
                    { "CopyFilesActivity", new CopyFilesActivity() },
                    { "CopyNIsAndDLLsActivity", new CopyImagesAndLibrariesActivity() },
                    { "DateTimeActivity", new UtcDateTimeActivity() },
                    { "DumpProcessThreadsActivity", new DumpProcessThreadsActivity() },
                    { "FileExistsActivity", new CheckIfFileExistsActivity() },
                    { "ForceBlueScreenActivity", new ForceBlueScreenActivity() },
                    { "GetLoggedOnUsersActivity", new GetCurrentLoggedOnUsersActivity() },
                    { "GetOsFileVersionActivity", new GetOsFileVersionActivity() },
                    { "GetProcessIdActivity", new GetProcessIdsActivity() },
                    { "GetSystemUptimeActivity", new GetSystemUptimeActivity() },
                    { "GetTimeSkewActivity", new GetSystemTimeSkewActivity() },
                    { "InstallSysInternalsActivity", new InstallSysInternalsActivity() },
                    { "ModifyConfigurationFileActivity", new EditConfigurationFileActivity() },
                    { "PingActivity", new PingResponseActivity() },
                    { "PortConnectivityActivity", new PortConnectivityActivity() },
                    { "ReadFileContentsActivity", new ReadFileContentsActivity() },
                    { "RenameMachineActivity", new RenameMachineActivity() },
                    { "RestartServiceActivity", new RestartServiceActivity() },
                    { "SetSymbolsEnvironmentPath", new SetSymbolServerEnvironmentPathActivity() },
                    { "StartSecureDeleteActivity", new StartSecureDeleteActivity() },
                    { "WindowsUpdateActivity", new WindowsUpdateActivity() },
                    { "WebStringActivity", new WebStringActivity() }
                };

                SwedishCodeActivity <object> newSwedishCodeActivity = (SwedishCodeActivity <object>)newDictionary[command];
                if (!string.IsNullOrWhiteSpace(firstParameter))
                {
                    newSwedishCodeActivity.FirstInArgument = firstParameter;
                }

                if (!string.IsNullOrWhiteSpace(secondParameter))
                {
                    newSwedishCodeActivity.SecondInArgument = secondParameter;
                }

                if (!string.IsNullOrWhiteSpace(thirdParameter))
                {
                    newSwedishCodeActivity.ThirdInArgument = thirdParameter;
                }

                SqlWorkflowInstanceStore newSqlWorkflowInstanceStore = new SqlWorkflowInstanceStore("Server=192.168.0.252,1433\\SQL2008EXPRESS;Initial Catalog=WorkflowInstanceStore;Integrated Security=SSPI")
                {
                    HostLockRenewalPeriod            = TimeSpan.FromSeconds(1),
                    InstanceCompletionAction         = InstanceCompletionAction.DeleteNothing,
                    InstanceLockedExceptionAction    = InstanceLockedExceptionAction.AggressiveRetry,
                    RunnableInstancesDetectionPeriod = TimeSpan.FromSeconds(1) // Minimum allowed value.
                };

                InstanceHandle             workflowInstanceStoreHandle = newSqlWorkflowInstanceStore.CreateInstanceHandle();
                CreateWorkflowOwnerCommand createWorkflowOwnerCommand  = new CreateWorkflowOwnerCommand();
                InstanceView newInstanceView = newSqlWorkflowInstanceStore.Execute(workflowInstanceStoreHandle, createWorkflowOwnerCommand, TimeSpan.FromSeconds(30));
                newSqlWorkflowInstanceStore.DefaultInstanceOwner = newInstanceView.InstanceOwner;

                WorkflowApplication newWorkflowApplication = new WorkflowApplication(newSwedishCodeActivity, new WorkflowIdentity
                {
                    // The Dictionary will throw for non-found key before we ever get here, so no need to validate input.
                    Name    = command,
                    Version = new Version(0, 1, 0, 0)
                })
                {
                    InstanceStore          = newSqlWorkflowInstanceStore,
                    SynchronizationContext = SynchronizationContext.Current
                };

                newWorkflowApplication.Persist();
                ResultObject = new object();
                newWorkflowApplication.Completed += delegate(WorkflowApplicationCompletedEventArgs e)
                {
                    if (e.CompletionState == ActivityInstanceState.Faulted)
                    {
                        EventLog.WriteEntry("Felsökning.Tomte.AdminService", $"Workflow {e.InstanceId} has faulted.\nException: {e.TerminationException.GetType().FullName}\nMessage:{e.TerminationException.Message}");
                        syncEvent.Set();
                    }
                    else if (e.CompletionState == ActivityInstanceState.Canceled)
                    {
                        EventLog.WriteEntry("Felsökning.Tomte.AdminService", $"Workflow {e.InstanceId} has been canceled.");
                        syncEvent.Set();
                    }
                    else
                    {
                        // Since the result can be *anything*, let's not treat it like a string.
                        EventLog.WriteEntry("Felsökning.Tomte.AdminService", $"Workflow {e.InstanceId} completed. Result: {e.Outputs["Result"]}");
                        ResultObject = e.Outputs["Result"];
                        syncEvent.Set();
                    }
                };

                newWorkflowApplication.Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
                {
                    // The workflow aborted, so let's find out why.
                    EventLog.WriteEntry("Felsökning.Tomte.AdminService", $"Workflow {e.InstanceId} has been aborted.\nException: {e.Reason.GetType().FullName}\nMessage:{e.Reason.Message}");
                    syncEvent.Set();
                };

                newWorkflowApplication.Idle = delegate(WorkflowApplicationIdleEventArgs e)
                {
                    // TODO: [FUTURE] Need to handle future persistence maintenance.
                    EventLog.WriteEntry("Felsökning.Tomte.AdminService", $"Workflow {e.InstanceId} has entered the Idle state.");
                    syncEvent.Set();
                };

                newWorkflowApplication.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e)
                {
                    EventLog.WriteEntry("Felsökning.Tomte.AdminService", $"Workflow {e.InstanceId} has entered PersistableIdle.");
                    syncEvent.Set();

                    // Runtime will persist.
                    return(PersistableIdleAction.Persist);
                };

                newWorkflowApplication.Unloaded = delegate(WorkflowApplicationEventArgs e)
                {
                    EventLog.WriteEntry("Felsökning.Tomte.AdminService", $"Workflow {e.InstanceId} has been unloaded.");
                    syncEvent.Set();
                };

                newWorkflowApplication.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
                {
                    // Log the unhandled exception.
                    EventLog.WriteEntry("Felsökning.Tomte.AdminService",
                                        !string.IsNullOrWhiteSpace(e.UnhandledException.InnerException?.Message)
                            ? $"Workflow {e.InstanceId} has reached an AggregateException in OnUnhandledException.\nException Source: {e.ExceptionSource.DisplayName}\nException Instance ID: {e.ExceptionSourceInstanceId}\nException: {e.UnhandledException.InnerException.GetType().FullName}\nMessage: {e.UnhandledException.InnerException.Message}\nFirstArgument: {firstParameter}\nSecondArgument: {secondParameter}"
                            : $"Workflow {e.InstanceId} has reached OnUnhandledException.\nException Source: {e.ExceptionSource.DisplayName}\nException Instance ID: {e.ExceptionSourceInstanceId}\nException: {e.UnhandledException.GetType().FullName}\nMessage: {e.UnhandledException.Message}\nFirstArgument: {firstParameter}\nSecondArgument: {secondParameter}");

                    syncEvent.Set();

                    // Instruct the runtime to terminate the workflow.
                    // The other viable choices here are 'Abort' or 'Cancel'
                    return(UnhandledExceptionAction.Terminate);
                };

                newWorkflowApplication.Run();

                // Because a new thread is spawned, we need to wait for it to complete before we can move on.
                syncEvent.WaitOne();

                // Instance MUST be unloaded to update the SQL record. One would think this would happen on the overridden delegate methods (e.g.: Completed,OnUnhandledException, etc.)
                // but testing has proven this to not be the case.
                newWorkflowApplication.Unload(TimeSpan.FromSeconds(30));

                // Now, we dump the instance owner.
                DeleteWorkflowOwnerCommand newDeleteWorkflowOwnerCommand = new DeleteWorkflowOwnerCommand();
                newSqlWorkflowInstanceStore.Execute(
                    workflowInstanceStoreHandle,
                    newDeleteWorkflowOwnerCommand,
                    TimeSpan.FromSeconds(30));
            }

            GC.Collect();
        }
        static void Main(string[] args)
        {
            // create the workflow app and add handlers for the Idle and Completed actions
            WorkflowApplication app = new WorkflowApplication(new Sequence1());

            //setup persistence
            InstanceStore  store  = new SqlWorkflowInstanceStore(@"Data Source=.\SQLEXPRESS;Initial Catalog=WF45GettingStartedTutorial;Integrated Security=True");
            InstanceHandle handle = store.CreateInstanceHandle();
            InstanceView   view   = store.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));

            handle.Free();
            store.DefaultInstanceOwner = view.InstanceOwner;
            app.InstanceStore          = store;


            app.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                syncEvent.Set();
                return(PersistableIdleAction.Unload);
            };

            app.Unloaded = delegate(WorkflowApplicationEventArgs e)
            {
                syncEvent.Set();
            };

            app.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                Console.WriteLine("Workflow {0} Completed.", e.InstanceId);
                syncEvent.Set();
            };

            // start the application
            id = app.Id;
            app.Run();
            syncEvent.WaitOne();

            // resume bookmark 1
            string text = Console.ReadLine();

            app = new WorkflowApplication(new Sequence1());
            app.InstanceStore = store;

            app.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                syncEvent.Set();
                return(PersistableIdleAction.Unload);
            };

            app.Completed = (workflowApplicationCompletedEventArgs) =>
            {
                Console.WriteLine("WF Bookmark1 has Completed in the {0} state.",
                                  workflowApplicationCompletedEventArgs.CompletionState);
                syncEvent.Set();
            };
            app.Unloaded = (workflowApplicationEventArgs) =>
            {
                Console.WriteLine("WF Bookmark1 unloaded");
                syncEvent.Set();
            };

            app.Load(id);
            app.ResumeBookmark("readText", text);
            syncEvent.WaitOne();

            // resume bookmark 2
            int number = ReadNumberFromConsole();

            app = new WorkflowApplication(new Sequence1());
            app.InstanceStore = store;
            app.Completed     = (workflowApplicationCompletedEventArgs) =>
            {
                Console.WriteLine("WF Bookmark2 has Completed in the {0} state.",
                                  workflowApplicationCompletedEventArgs.CompletionState);
                syncEvent.Set();
            };
            app.Unloaded = (workflowApplicationEventArgs) =>
            {
                Console.WriteLine("WF Bookmark1 unloaded");
                syncEvent.Set();
            };

            app.Load(id);
            app.ResumeBookmark("readNumber", number);
            syncEvent.WaitOne();

            Console.WriteLine("");
            Console.WriteLine("Press [ENTER] to exit...");
            Console.ReadLine();
        }
    //end

    protected void btnEdit_ServerClick(object sender, EventArgs e)
    {
        if (this.DropDown_sp.SelectedValue.Length == 0)
        {
            MessageBox.Show(this, "请您选择审核结果");
        }
        else
        {
            Model.SelectRecord selectRecords = new Model.SelectRecord("view_DocumentInfo", "", "*", "where id='" + id + "'");
            DataTable          dt            = BLL.SelectRecord.SelectRecordData(selectRecords).Tables[0];
            //ziyunhx add 2013-8-5 workflow Persistence
            if (dt == null)
            {
                return;
            }
            Model.SelectRecord selectRecord = new Model.SelectRecord("WorkFlow", "", "*", "where id='" + dt.Rows[0]["WorkFlowID"].ToString() + "'");
            DataTable          table        = BLL.SelectRecord.SelectRecordData(selectRecord).Tables[0];

            string content = File.ReadAllText(System.Web.HttpContext.Current.Request.MapPath("../") + table.Rows[0]["URL"].ToString());

            instance = engineManager.createInstance(content, null, null);
            if (instanceStore == null)
            {
                instanceStore = new SqlWorkflowInstanceStore(SqlHelper.strconn);
                view          = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
                instanceStore.DefaultInstanceOwner = view.InstanceOwner;
            }
            instance.InstanceStore = instanceStore;
            Guid guid = new Guid(dt.Rows[0]["FlowInstranceID"].ToString());
            instance.Load(guid);
            //end


            if (this.DropDown_sp.SelectedValue == "true")
            {
                string[] s = dt.Rows[0]["OID"].ToString().Split(new char[] { ',' });
                if (s[s.Length - 1] == "1")
                {
                    Model.SelectRecord selectExecut = new Model.SelectRecord("WorkFlowExecution", "", "*", "where DID='" + id + "' and step ='" + dt.Rows[0]["WStep"].ToString() + "' and UID='" + this.Session["admin"].ToString() + "'");
                    DataTable          executdt     = BLL.SelectRecord.SelectRecordData(selectExecut).Tables[0];
                    if (executdt.Rows.Count > 0)
                    {
                        MessageBox.ShowAndRedirect(this, "该公文您已审核,请等待其他人审核!", "/document/DocumentList.aspx");
                    }
                    else
                    {
                        Model.SelectRecord selectExecutCount = new Model.SelectRecord("WorkFlowExecution", "", "distinct UID", "where DID='" + id + "' and step ='" + dt.Rows[0]["WStep"].ToString() + "'");
                        DataTable          dtcount           = BLL.SelectRecord.SelectRecordData(selectExecutCount).Tables[0];

                        string where = "where IsState=2 AND (1=2 ";

                        string[] str = dt.Rows[0]["OID"].ToString().Split(new char[] { ',' });
                        for (int j = 1; j < str.Length - 1; j++)
                        {
                            where += "OR OID like '%" + str[j].ToString() + "%' ";
                        }
                        where += ") order by id desc";

                        Model.SelectRecord selectUserCount = new Model.SelectRecord("Users", "", "ID", where);
                        DataTable          usercount       = BLL.SelectRecord.SelectRecordData(selectUserCount).Tables[0];

                        if (dtcount.Rows.Count + 1 == usercount.Rows.Count)
                        {
                            if (instance.GetBookmarks().Count(p => p.BookmarkName == dt.Rows[0]["value"].ToString()) == 1)
                            {
                                instance.ResumeBookmark(dt.Rows[0]["value"].ToString(), this.DropDown_sp.SelectedValue.ToString());
                            }
                        }
                    }
                }
                else
                {
                    //一旦审批未通过,删除该公文当前流转步骤信息
                    BLL.GeneralMethods.GeneralDelDB("WorkFlowExecution", "where DID ='" + id + "' and step='" + dt.Rows[0]["WStep"].ToString() + "'");
                    if (instance.GetBookmarks().Count(p => p.BookmarkName == dt.Rows[0]["value"].ToString()) == 1)
                    {
                        instance.ResumeBookmark(dt.Rows[0]["value"].ToString(), this.DropDown_sp.SelectedValue.ToString());
                    }
                }

                Model.WorkFlowExecution workexe = new Model.WorkFlowExecution
                {
                    DID    = dt.Rows[0]["ID"].ToString(),
                    UID    = this.Session["admin"].ToString(),
                    step   = dt.Rows[0]["WStep"].ToString(),
                    Remark = this.txtSP.Value.Trim(),
                    Result = "1",
                };

                BLL.WorkFlowExecution.Add(workexe);
            }
            else
            {
                Model.WorkFlowExecution workexe = new Model.WorkFlowExecution
                {
                    DID    = dt.Rows[0]["ID"].ToString(),
                    UID    = this.Session["admin"].ToString(),
                    step   = dt.Rows[0]["WStep"].ToString(),
                    Remark = this.txtSP.Value.Trim(),
                    Result = "2",
                };

                BLL.WorkFlowExecution.Add(workexe);

                if (instance.GetBookmarks().Count(p => p.BookmarkName == dt.Rows[0]["value"].ToString()) == 1)
                {
                    instance.ResumeBookmark(dt.Rows[0]["value"].ToString(), this.DropDown_sp.SelectedValue.ToString());
                }
            }
            UserOperatingManager.InputUserOperating(this.Session["admin"].ToString(), "公文管理", "公文审核" + dt.Rows[0]["Name"].ToString() + "的信息成功");
            MessageBox.ShowAndRedirect(this, "审核公文成功!", "/document/DocumentList.aspx");

            instance.Unload();
        }
    }