Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            bool running = true;

            // create the workflow application and start its execution
            AutoResetEvent      syncEvent   = new AutoResetEvent(false);
            WorkflowApplication application = new WorkflowApplication(CreateGuessingGameWF());

            application.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { running = false; syncEvent.Set(); };
            application.Idle      = delegate(WorkflowApplicationIdleEventArgs e)
            {
                syncEvent.Set();
            };
            application.Run();

            // main loop (manages bookmarks)
            while (running)
            {
                if (!syncEvent.WaitOne(10, false))
                {
                    if (running)
                    {
                        // if there are pending bookmarks...
                        if (HasPendingBookmarks(application))
                        {
                            // get the name of the bookmark
                            string bookmarkName = application.GetBookmarks()[0].BookmarkName;

                            // resume the bookmark (passing the data read from the console)
                            application.ResumeBookmark(bookmarkName, Console.ReadLine());

                            syncEvent.WaitOne();
                        }
                    }
                }
            }

            // wait for user input
            Console.ReadLine();
        }
Ejemplo n.º 2
0
        public bool Resume(Activity activity, Guid appId, string bookmarkName, object bookmarkArgs)
        {
            var unloadedSignal = new AutoResetEvent(false);

            var app = new WorkflowApplication(activity)
            {
                InstanceStore   = _store,
                PersistableIdle = eventArgs => PersistableIdleAction.Unload,
                Aborted         = obj =>
                {
                    unloadedSignal.Set();
                    Trace.TraceError("abort");
                },
                OnUnhandledException = (a) =>
                {
                    Trace.TraceError($"exception:{a.UnhandledException.Message}");
                    return(UnhandledExceptionAction.Cancel);
                },
                Unloaded = _ =>
                {
                    unloadedSignal.Set();
                    Trace.TraceError("unloaded");
                },
                Completed = _ =>
                {
                    unloadedSignal.Set();
                    Trace.TraceError("completed");
                }
            };

            app.Load(appId);
            var result = app.ResumeBookmark(bookmarkName, bookmarkArgs);

            if (result != BookmarkResumptionResult.Success)
            {
                return(false);
            }
            unloadedSignal.WaitOne();
            return(true);
        }
Ejemplo n.º 3
0
        private void btnAssign_Click(object sender, RoutedEventArgs e)
        {
            if (lstLeads.SelectedIndex >= 0)
            {
                Lead l  = (Lead)lstLeads.Items[lstLeads.SelectedIndex];
                Guid id = l.WorkflowID;

                WorkflowApplication i = new WorkflowApplication(new EnterLead());

                SetupInstance(i);
                i.Load(id);

                try
                {
                    i.ResumeBookmark("GetAssignment", txtAgent.Text);
                }
                catch (Exception e2)
                {
                    AddEvent(e2.Message);
                }
            }
        }
Ejemplo n.º 4
0
        private void btnAssign_Click(object sender, RoutedEventArgs e)
        {
            if (lstLeads.SelectedIndex >= 0)
            {
                Lead l  = (Lead)lstLeads.Items[lstLeads.SelectedIndex];
                Guid id = l.WorkflowID;

                LeadDataDataContext dc = new LeadDataDataContext(_connectionString);
                dc.Refresh(RefreshMode.OverwriteCurrentValues, dc.Leads);
                l = dc.Leads.SingleOrDefault <Lead>(x => x.WorkflowID == id);
                if (l != null)
                {
                    l.AssignedTo = txtAgent.Text;
                    l.Status     = "Assigned";
                    dc.SubmitChanges();

                    // Clear the input
                    txtAgent.Text = "";
                }

                // Update the grid
                lstLeads.Items[lstLeads.SelectedIndex] = l;
                lstLeads.Items.Refresh();

                WorkflowApplication i = new WorkflowApplication(new EnterLead());

                SetupInstance(i);
                i.Load(id);

                try
                {
                    i.ResumeBookmark("GetAssignment", l);
                }
                catch (Exception e2)
                {
                    AddEvent(e2.Message);
                }
            }
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //获取选中的值
        string bestSolutionWorkflowId = null;

        foreach (CrowdTask ct in list)
        {
            RadioButton rb = (RadioButton)this.FindControl(ct.taskWorkflowId);

            if (rb.Checked)
            {
                bestSolutionWorkflowId = ct.taskWorkflowId;
                break;
            }
        }
        //将选中的结果保存保存起来。
        WorkflowApplication wa = MyWorkflowInstance.getSolveVotingWorkflowApplication(taskWorkflowId);

        wa.ResumeBookmark(BookmarkName.SolveVoting, bestSolutionWorkflowId);
        //跳票完成跳转
        Server.Transfer("solveVoteCompeleted.aspx");
    }
Ejemplo n.º 6
0
        private static void OrderComplete(
            Guid instanceId, InstanceStore store, IItemSupport extension)
        {
            WorkflowApplication wfApp = SetupInstance(
                ref instanceId, store, extension);

            wfApp.Completed = (e) =>
            {
                Console.WriteLine("{0} Is Completed", e.InstanceId);
                List <Item> items = e.Outputs["Items"] as List <Item>;
                Console.WriteLine("\nOrdered Items:");
                foreach (Item i in items)
                {
                    Console.WriteLine(
                        "ItemId={0}, Quantity={1}, UnitPrice={2}, Total={3}",
                        i.ItemId, i.Quantity, i.UnitPrice, i.TotalPrice);
                }
            };

            wfApp.ResumeBookmark("OrderComplete", null);
            _unloadedEvent.WaitOne(5000);
        }
Ejemplo n.º 7
0
        private static void SendInstance(string customerName, string bookmarkName)
        {
            if (!customers.Exists(c => c.Name == customerName))
            {
                Console.WriteLine(string.Format("No such customer {0}.", customerName));
                return;
            }

            var customer = customers.Find(c => c.Name == customerName);

            if (customer.InstanceId == "")
            {
                Console.WriteLine(string.Format("Customer {0} does not have workflow instance.", customerName));
                return;
            }

            SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(connectionString);

            WorkflowApplication.CreateDefaultInstanceOwner(store, null, WorkflowIdentityFilter.Any);

            WorkflowApplicationInstance instance =
                WorkflowApplication.GetInstance(new Guid(customer.InstanceId), store);

            Activity wf = GetWorkflow(customer.WorkflowId);

            if (wf == null)
            {
                Console.WriteLine(string.Format("Unknown workflow {0}", customer.WorkflowId));
                return;
            }
            WorkflowApplication wfApp =
                new WorkflowApplication(wf, instance.DefinitionIdentity);

            ConfigureWFApp(wfApp, customer);
            wfApp.Load(instance);
            instanceUnloaded.Reset();
            wfApp.ResumeBookmark(bookmarkName, null);
        }
Ejemplo n.º 8
0
        private void ResumeBookmark(Guid workflowInstanceId,
                                    Func <WorkflowIdentity, Activity> workflowMap, string bookmarkName, object bookmarkResumeContext)
        {
            // >>>> RESUME A WORKFLOW <<<<
            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(workflowInstanceId, _store);

            Activity workflow = workflowMap(instance.DefinitionIdentity);

            // Associate the WorkflowApplication with the correct definition (a name & version)
            WorkflowApplication wfApp = new WorkflowApplication(workflow, instance.DefinitionIdentity);


            // Configure the extensions and lifecycle handlers.
            // Do this before the instance is loaded. Once the instance is
            // loaded it is too late to add extensions.
            ConfigureWorkflowApplication(wfApp);

            // Load the workflow.
            wfApp.Load(instance); //takes a Guid InstanceId or WorkflowApplicationInstance instance from store

            // Resume the workflow.
            wfApp.ResumeBookmark(bookmarkName, bookmarkResumeContext);
        }
Ejemplo n.º 9
0
        // >>>> RESUME A WORKFLOW <<<<
        public WorkflowResult ResumeBookmark(Guid workflowInstanceId, Func <WorkflowIdentity, Activity> workflowMap,
                                             string bookmarkName, object bookmarkResumeContext, Action <string> writelineListener = null)
        {
            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(workflowInstanceId, _store);

            Activity workflow = workflowMap(instance.DefinitionIdentity);

            // Associate the WorkflowApplication with the correct definition (a name & version)
            WorkflowApplication wfApp = new WorkflowApplication(workflow, instance.DefinitionIdentity);

            // Configure the extensions and lifecycle handlers.
            // Do this before the instance is loaded. Once the instance is
            // loaded it is too late to add extensions.
            ConfigureWorkflowApplication(wfApp, writelineListener);

            // Load the workflow.
            wfApp.Load(instance); //takes a Guid InstanceId or WorkflowApplicationInstance instance from store

            // Resume the workflow.
            wfApp.ResumeBookmark(bookmarkName, bookmarkResumeContext);

            return(WaitAndReturnData());
        }
Ejemplo n.º 10
0
        private void RunWorkflow(TrackingProfile profile, out MyTrackingParticipant participant)
        {
            AutoResetEvent completedEvent = new AutoResetEvent(false);
            AutoResetEvent idleEvent      = new AutoResetEvent(false);
            Activity       workflow       = CreateWorkflow(bookmarkName);

            participant = new MyTrackingParticipant
            {
                TrackingProfile = profile
            };

            WorkflowApplication wfApp = Utilities.CreateWorkflowApplication(workflow,
                                                                            /*store=*/ null,
                                                                            idleEvent,
                                                                            /*unloadedEvent=*/ null,
                                                                            completedEvent);

            wfApp.Extensions.Add(participant);
            wfApp.Run();
            idleEvent.WaitOne(TimeSpan.FromSeconds(2));
            wfApp.ResumeBookmark(bookmarkName, bookmarkData);
            completedEvent.WaitOne(TimeSpan.FromSeconds(2));
        }
Ejemplo n.º 11
0
        public static void ResumeFlow(string quoteId, List <WorkFlowApproval> addtionlApprovals)
        {
            relatedQuoteId = quoteId;
            WorkFlowApproval approval = eQuotationContext.Current.WorkFlowApproval.OrderByDescending(q => q.LevelNum).FirstOrDefault(q => q.TypeID == quoteId && q.WorkFlowID != "");

            if (approval != null)
            {
                string strSqlCmd =
                    String.Format(
                        "select top 1 Id,BlockingBookmarks from [System.Activities.DurableInstancing].[InstancesTable] where id='{0}'",
                        approval.WorkFlowID);
                DataTable dt = dbGetDataTable("WFDB", strSqlCmd);
                if (dt.Rows.Count == 1)
                {
                    string bookmark     = dt.Rows[0]["BlockingBookmarks"].ToString();
                    string bookmarkName = bookmark.Substring(1, bookmark.IndexOf(":") - 1);

                    AutoResetEvent      syncEvent = new AutoResetEvent(false);
                    WorkflowApplication wfApp     = GetWorkFlowApplication(null, syncEvent);
                    Guid instanceId = new Guid(approval.WorkFlowID);
                    wfApp.Load(instanceId);
                    wfApp.ResumeBookmark(bookmarkName, addtionlApprovals);
                    wfApp.Run();
                    syncEvent.WaitOne();
                }
                else
                {
                    SendErrorMail("Bookmark is not found in InstancesTable, resume flow fail!");
                    ApprovalResult = ApprovalResult.ApprovalBookmarkNotFound;
                }
            }
            else
            {
                SendErrorMail("Approval is not found in WorkFlowApproval Table, resume flow fail!");
                ApprovalResult = ApprovalResult.WaitingApproverNotFound;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// (从数据库中)恢复工作流
        /// </summary>
        /// <param name="ActivityType">工作流类型</param>
        /// <param name="WorkFlowID">要恢复的工作流ID</param>
        /// <param name="BookName">恢复的书签节点</param>
        /// <param name="Value">传入的值</param>
        public static RecoveryFlowState AwakenWorkFlow(Type ActivityType, Guid WorkFlowID, string BookName, object Value, Frm_BaseFlow Frm)
        {
            WorkflowApplication Instance = new WorkflowApplication((Activity)Activator.CreateInstance(ActivityType));

            Instance.InstanceStore = new SqlWorkflowInstanceStore("Data Source=.;Initial Catalog=MyOA;Integrated Security=True");
            BindLifeCycle(Frm, Instance);
            try
            {
                Instance.Load(WorkFlowID);
                Instance.ResumeBookmark(BookName, Value);
            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("尚未保留到实例存储区") > 0)
                {
                    return(RecoveryFlowState.NoSaveInstance);
                }
                if (ex.Message.IndexOf("其他实例所有者锁定了实例") > 0)
                {
                    return(RecoveryFlowState.OthersInUse);
                }
            }
            return(RecoveryFlowState.Done);
        }
Ejemplo n.º 13
0
        private void btnContinue_Click(object sender, EventArgs e)
        {
            //让工作流在书签的位置继续往下流动
            //WFApp.ResumeBookmark(txtBookMarkName.Text, int.Parse(txtMoney.Text));

            //从数据库中加载工作流实例的状态
            SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(connectionString);

            WorkflowApplication wfApp = new WorkflowApplication(new StateMoneyActivity1xaml());

            wfApp.InstanceStore = store;

            wfApp.Idle += OnWfAppIdel;
            wfApp.OnUnhandledException += OnWfAppException;
            wfApp.Unloaded              = a => { Console.WriteLine("工作流卸载了..."); };
            wfApp.Aborted = a => { Console.WriteLine("Aborted"); };

            //启用序列化必须使用此方法。
            wfApp.PersistableIdle = a => { return(PersistableIdleAction.Unload); };

            //加载数据库中的实例的状态。
            wfApp.Load(Guid.Parse(txtAppId.Text));
            wfApp.ResumeBookmark(txtBookMarkName.Text, int.Parse(txtMoney.Text));
        }
Ejemplo n.º 14
0
        private void EnterGuess_Click(object sender, EventArgs e)
        {
            if (WorkflowInstanceId == Guid.Empty)
            {
                MessageBox.Show("Please select a workflow.");
                return;
            }
            int guess;

            if (!Int32.TryParse(Guess.Text, out guess))
            {
                MessageBox.Show("Please enter an integer.");
                Guess.SelectAll();
                Guess.Focus();
                return;
            }

            var instance = _workflowApplication.GetInstance(this.WorkflowInstanceId);


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

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

            // Configure the extensions and lifecycle handlers.
            // Do this before the instance is loaded. Once the instance is
            // loaded it is too late to add extensions.

            // Configure the instance store, extensions, and
            // workflow lifecycle handlers.
            var events = _workflowApplication.ConfigureWorkflowApplication(wfApp);

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

            // Create game Id
            GameId = Guid.NewGuid();

            var game = new Game()
            {
                Id = GameId, InstanceId = WorkflowInstanceId, Guess = guess, WorkflowType = WorkflowType.SelectedItem.ToString(), MaxNumber = Convert.ToInt32(NumberRange.SelectedItem)
            };

            // Resume the workflow.
            wfApp.ResumeBookmark("Game", game);

            // Clear the Guess textbox.
            Guess.Clear();
            Guess.Focus();

            Game display = null;

            while (display == null)
            {
                display = RetrieveData();
            }

            UpdateStatus(string.Format("Lets see how well you did: \r\n\r\nGuess = {0}\r\n MaxNumber = {1}\r\nResult = {2}\r\nTurns = {3}\r\nWorkflowType = {4}", display.Guess, display.MaxNumber, display.Result, display.Turns, display.WorkflowType));
        }
Ejemplo n.º 15
0
        private TResponse execute <TRequest, TResponse>(TRequest request, string OperationName)
        {
            TimeSpan timeOut = TimeSpan.FromMinutes(1);

            Action waitOne = delegate()
            {
                s_syncEvent = null;
                if (instanceStore != null)
                {
                    s_syncEvent = s_unloadedEvent;
                    s_unloadedEvent.WaitOne();
                }
                else
                {
                    s_syncEvent = s_idleEvent;
                    s_idleEvent.WaitOne();
                }
            };

            Action correlate = delegate()
            {
                if (instanceStore is IStoreCorrelation)
                {
                    (instanceStore as IStoreCorrelation).Correlate();
                    this.WorkflowId = (instanceStore as IStoreCorrelation).Correlation.WorkflowId;
                }
            };

            WorkflowInstanceContext instanceContext = new WorkflowInstanceContext()
            {
                Request  = request,
                Response = default(TResponse)
            };

            WorkflowApplication wfApp = null;

            //Guid wfId = Guid.Empty;

            while (invokeMode != WorkflowInvokeMode.None)
            {
                if (invokeMode == WorkflowInvokeMode.Run)
                {
                    wfApp           = createWorkflowApplication(instanceContext);
                    this.WorkflowId = wfApp.Id;
                    (wfApp.InstanceStore as IStoreCorrelation).Correlation.WorkflowId = wfApp.Id;
                    resetEvents();
                    wfApp.Run(timeOut);
                    waitOne();
                }
                else if (invokeMode == WorkflowInvokeMode.ResumeBookmark)
                {
                    wfApp = createWorkflowApplication(instanceContext);
                    resetEvents();
                    correlate();

                    if (this.WorkflowId == Guid.Empty)
                    {
                        throw new Exception($"WorkflowId  missing on workflow with");
                    }

                    wfApp.Load(this.WorkflowId, timeOut);

                    var ext       = wfApp.Extensions;
                    var isWaiting = wfApp.GetBookmarks().FirstOrDefault(b => b.BookmarkName == OperationName);
                    if (isWaiting != null)
                    {
                        wfApp.ResumeBookmark(OperationName, "bookmark data", timeOut);
                        waitOne();
                    }
                    else
                    {
                        throw new Exception($"Bookmark {OperationName} missing on workflow with id {wfApp.Id}");
                    }
                }

                if (exception != null)
                {
                    throw exception;
                }
            }
            ;

            TResponse response = default(TResponse);

            try
            {
                response = (TResponse)instanceContext.Response;
            }
            catch (Exception exc) //TODO: System.InvalidCastException
            {
                throw exc;
            }

            return(response);
        }
        public static void Main(string[] args)
        {
            string bookmarkData       = "default bookmark data";
            Guid   workflowInstanceId = Guid.Empty;
            bool   createNewInstance  = true;
            bool   keepFiles          = false;
            bool   showUsage          = false;

            Console.WriteLine("BookmarkConsoleApp");

            for (int i = 0; i < args.Length; i++)
            {
                if (string.Equals("-storepath", args[i], StringComparison.CurrentCultureIgnoreCase))
                {
                    s_fileInstanceStorePath = args[++i];
                    //Type[] knownTypes = new Type[] { typeof(Variable<int>.VariableLocation) };
                    //FileStore = new FileInstanceStore(FileInstanceStorePath, knownTypes);
                    s_fileStore = new FileInstanceStore(s_fileInstanceStorePath);
                    Console.WriteLine("Specified -storepath value = {0}", s_fileInstanceStorePath);
                }
                else if (string.Equals("-keepFiles", args[i], StringComparison.CurrentCultureIgnoreCase))
                {
                    keepFiles = true;
                    Console.WriteLine("Specified -keepFiles");
                }
                else if (string.Equals("/?", args[i], StringComparison.CurrentCultureIgnoreCase))
                {
                    showUsage = true;
                    break;
                }
                else
                {
                    Console.WriteLine("Unrecognized argument - {0}", args[i]);
                    showUsage = true;
                    break;
                }
            }

            if (showUsage || args.Length == 0)
            {
                PrintUsage();
                return;
            }

            if (s_fileStore != null)
            {
                s_fileStore.KeepInstanceDataAfterCompletion = keepFiles;
            }

            WorkflowApplication wfApp = CreateWorkflowApplication();

            if (s_fileStore != null)
            {
                Console.WriteLine("Create a new instance? (y/n, y is the default)");
                string createNewResponse = Console.ReadLine();
                if (string.Equals("n", createNewResponse, StringComparison.CurrentCultureIgnoreCase))
                {
                    createNewInstance = false;
                }

                if (!createNewInstance)
                {
                    Console.WriteLine("What instance id do you want to load?");
                    string instanceIdString = Console.ReadLine();
                    workflowInstanceId = new Guid(instanceIdString);
                }
            }

            if (createNewInstance)
            {
                workflowInstanceId = wfApp.Id;
                wfApp.Run();
                if (s_fileStore != null)
                {
                    s_unloadedEvent.WaitOne();
                }
                else
                {
                    s_idleEvent.WaitOne();
                }
            }

            string bookmarkName = workflowInstanceId.ToString();

            while (true)
            {
                Console.WriteLine();
                Console.WriteLine("What string data should do you want to pass to the bookmark? (type stop to complete workflow)");
                bookmarkData = Console.ReadLine();

                if (s_fileStore != null)
                {
                    wfApp = CreateWorkflowApplication();
                    wfApp.Load(workflowInstanceId);
                }

                wfApp.ResumeBookmark(bookmarkName, bookmarkData);
                if (string.Compare(bookmarkData, "stop", true) == 0)
                {
                    s_completedEvent.WaitOne();
                    break;
                }
                if (s_fileStore != null)
                {
                    s_unloadedEvent.WaitOne();
                }
                else
                {
                    s_idleEvent.WaitOne();
                }
            }

            Console.WriteLine("Press <enter> to finish");
            Console.ReadLine();
        }
        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();
        }
Ejemplo n.º 18
0
 private void btnContinue_Click(object sender, EventArgs e)
 {
     workflowApplication.ResumeBookmark(txtBookMarkName.Text, int.Parse(txtMoney.Text));
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Invoked when a web request arrives.
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                // bind ourselves to the context
                Context = context;

                // request was for a resource
                if (Request[ResourceQueryKey] != null)
                {
                    // handle it and return, no need to deal with workflow
                    ProcessResourceRequest(Request[ResourceQueryKey]);
                    return;
                }

                // obtain our activity instance
                Activity = CreateActivity();

                // configure application
                WorkflowApplication = Request[InstanceIdQueryKey] == null ? new WorkflowApplication(Activity, GetArguments()) : new WorkflowApplication(Activity);
                WorkflowApplication.Extensions.Add <ITwilioContext>(() => this);
                WorkflowApplication.SynchronizationContext = new SynchronizedSynchronizationContext();
                WorkflowApplication.InstanceStore          = CreateInstanceStore();
                WorkflowApplication.Aborted              = OnAborted;
                WorkflowApplication.Completed            = OnCompleted;
                WorkflowApplication.Idle                 = OnIdle;
                WorkflowApplication.OnUnhandledException = OnUnhandledException;
                WorkflowApplication.PersistableIdle      = OnPersistableIdle;
                WorkflowApplication.Unloaded             = OnUnloaded;

                // attempt to resolve current instance id and reload workflow state
                if (Request[InstanceIdQueryKey] != null)
                {
                    WorkflowApplication.Load(Guid.Parse(Request[InstanceIdQueryKey]), Timeout);
                }

                // postback to resume a bookmark
                if (Request[BookmarkQueryKey] != null)
                {
                    WorkflowApplication.ResumeBookmark(Request[BookmarkQueryKey], GetPostData(), Timeout);
                }
                else
                {
                    // begin running the workflow from the start
                    WorkflowApplication.Run(Timeout);
                }

                // throw exception
                if (UnhandledExceptionInfo != null)
                {
                    UnhandledExceptionInfo.Throw();
                }

                // strip off temporary attributes
                foreach (var element in TwilioResponse.DescendantsAndSelf())
                {
                    foreach (var attribute in element.Attributes())
                    {
                        if (attribute.Name.Namespace == tmpNs)
                        {
                            attribute.Remove();
                        }
                    }
                }

                // write finished twilio output
                Response.ContentType = "text/xml";
                using (var wrt = XmlWriter.Create(Response.Output))
                    TwilioResponse.WriteTo(wrt);

                // if we've reached the end, no need to force unload
                WorkflowApplication = null;
            }
            finally
            {
                // clean up application if possible
                if (WorkflowApplication != null)
                {
                    try
                    {
                        WorkflowApplication.Unload(Timeout);
                        WorkflowApplication = null;
                    }
                    catch
                    {
                        // ignore
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public TResponse StartWorkflow <TRequest, TResponse>(TRequest request, string OperationName)
        {
            TimeSpan timeOut = TimeSpan.FromMinutes(1);

            Action waitOne = delegate()
            {
                s_syncEvent = null;
                if (instanceStore != null)
                {
                    s_syncEvent = s_unloadedEvent;
                    s_unloadedEvent.WaitOne();
                }
                else
                {
                    s_syncEvent = s_idleEvent;
                    s_idleEvent.WaitOne();
                }
            };

            WorkflowInstanceContext instanceContext = new WorkflowInstanceContext()
            {
                Request  = request,
                Response = default(TResponse)
            };

            invokeMode = WorkflowInvokeMode.Run;

            WorkflowApplication wfApp = null;
            Guid wfId = Guid.Empty;

            while (invokeMode != WorkflowInvokeMode.None)
            {
                if (invokeMode == WorkflowInvokeMode.Run)
                {
                    wfApp = createWorkflowApplication(instanceContext);
                    wfId  = wfApp.Id;
                    resetEvents();
                    wfApp.Run(timeOut);
                    waitOne();
                }
                else if (invokeMode == WorkflowInvokeMode.ResumeBookmark)
                {
                    wfApp = createWorkflowApplication(instanceContext);
                    resetEvents();
                    wfApp.Load(wfId, timeOut);
                    var isWaiting = wfApp.GetBookmarks().FirstOrDefault(b => b.BookmarkName == OperationName);
                    if (isWaiting != null)
                    {
                        wfApp.ResumeBookmark(OperationName, "bookmark data", timeOut);
                        waitOne();
                    }
                    else
                    {
                        throw new Exception($"Bookmark {OperationName} missing on workflow with id {wfApp.Id}");
                    }
                }
            }
            ;


            TResponse response = default(TResponse);

            try
            {
                response = (TResponse)instanceContext.Response;
            }
            catch
            {
            }

            return(response);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 此代码将创建一个 WorkflowApplication,订阅三个工作流生命周期事件,通过调用 Run 来启动工作流,然后等待工作流完成。 工作流完成时,将设置 AutoResetEvent,并且宿主应用程序也完成。
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //Activity workflow1 = new KeyActivity();
            //WorkflowInvoker.Invoke(workflow1);

            AutoResetEvent syncEvent = new AutoResetEvent(false);
            AutoResetEvent idleEvent = new AutoResetEvent(false);

            var inputs = new Dictionary <string, object>()
            {
                { "MaxNumber", 100 }
            };

            WorkflowApplication wfApp =
                //new WorkflowApplication(new KeyActivity(), inputs);
                //new WorkflowApplication(new FlowActivity(), inputs);
                new WorkflowApplication(new StateMachineActivity(), inputs);


            wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                int Turns = Convert.ToInt32(e.Outputs["Turns"]);
                Console.WriteLine("祝贺! 你用了 {0} 次得以猜中.", Turns);

                syncEvent.Set();
            };


            wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
            {
                Console.WriteLine(e.Reason);
                syncEvent.Set();
            };

            wfApp.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
            {
                Console.WriteLine(e.UnhandledException.ToString());
                return(UnhandledExceptionAction.Terminate);
            };

            //每次工作流变为空闲状态等待下一个猜测时,都会调用此处理程序并设置 idleAction AutoResetEvent。
            wfApp.Idle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                idleEvent.Set();
            };

            wfApp.Run();


            //syncEvent.WaitOne();

            //下面步骤中的代码使用 idleEvent 和 syncEvent 来确定工作流是在等待下一个猜测还是已完成。
            // 在本示例中,宿主应用程序在 Completed 和 Idle 处理程序中使用自动重置事件将宿主应用程序与工作流的进度同步。 在继续执行书签之前,不需要阻止并等待工作流变为空闲状态,但在此示例中需要同步事件,以使宿主知道工作流是否已完成,或是否在等待使用 Bookmark 的更多用户输入。
            // Loop until the workflow completes.
            WaitHandle[] handles = new WaitHandle[] { syncEvent, idleEvent };
            while (WaitHandle.WaitAny(handles) != 0)
            {
                // Gather the user input and resume the bookmark.
                bool validEntry = false;
                while (!validEntry)
                {
                    int Guess;
                    if (!Int32.TryParse(Console.ReadLine(), out Guess))
                    {
                        Console.WriteLine("只能猜整数.");
                    }
                    else
                    {
                        validEntry = true;
                        //此句保证工作流迭代继续,相当于continue / goto EnterGuess
                        wfApp.ResumeBookmark("EnterGuess", Guess);
                    }
                }
            }
        }
Ejemplo n.º 22
0
 public void Resume(Object value)
 {
     _host.ResumeBookmark(BookmarkActivity.BookmarkName, value);
 }
Ejemplo n.º 23
0
    //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();
        }
    }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);
            AutoResetEvent idleEvent = new AutoResetEvent(false);

            //参数
            var inputs = new Dictionary <string, object>()
            {
                { "MaxNumber", 100 }
            };
            //WorkflowApplication 为执行工作流(包括生命周期事件通知、执行控制、书签恢复和持久性)提供更丰富的模型。 此示例使用书签并且将 WorkflowApplication 用于承载工作流
            WorkflowApplication wfApp = new WorkflowApplication(new FlowchartNumberGuessWorkflow(), inputs);

            wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                int Turns = Convert.ToInt32(e.Outputs["Turns"]);
                Console.WriteLine("Congratulations, you guessed the number in {0} turns.", Turns);
                syncEvent.Set();
            };


            wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
            {
                Console.WriteLine(e.Reason);
                syncEvent.Set();
            };

            wfApp.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
            {
                Console.WriteLine(e.UnhandledException.ToString());
                return(UnhandledExceptionAction.Terminate);
            };

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


            wfApp.Run();

            // Loop until the workflow completes.
            //WaitHandle[] handles = new WaitHandle[] { syncEvent, idleEvent };
            //while (WaitHandle.WaitAny(handles) != 0)
            //{
            //    // Gather the user input and resume the bookmark.

            //}

            while (true)
            {
                bool validEntry = false;
                while (!validEntry)
                {
                    int Guess;
                    if (!Int32.TryParse(Console.ReadLine(), out Guess))
                    {
                        Console.WriteLine("Please enter an integer.");
                    }
                    else
                    {
                        validEntry = true;
                        wfApp.ResumeBookmark("EnterGuess", Guess);
                    }
                }
            }
        }
Ejemplo n.º 25
0
        public ActionResult DrafterToNextState(ItServiceItem isi, Guid instanceId, string NextLink, string libid)  //起草者到下一环节
        {
            string[] strs = NextLink.Trim().Split('(');

            AutoResetEvent syncEvent = new AutoResetEvent(false);

            WorkflowApplication wfApp = new WorkflowApplication(new ItService())
            {
                InstanceStore   = CreateInstanceStore(),
                PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e)
                {
                    //var ex = e.GetInstanceExtensions<CustomTrackingParticipant>();
                    // Outputs = ex.First().Outputs.ToString();`
                    return(PersistableIdleAction.Unload);
                },
                Completed = delegate(WorkflowApplicationCompletedEventArgs e)
                {
                },
                Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
                {
                },
                Unloaded = delegate(WorkflowApplicationEventArgs e)
                {
                    syncEvent.Set();
                },
                OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
                {
                    return(UnhandledExceptionAction.Terminate);
                },
                Idle = delegate(WorkflowApplicationIdleEventArgs e)
                {
                }
            };
            var StateTracker = new StateMachineStateTracker(wfApp.WorkflowDefinition); //当前状态追踪

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

                return(Json(json, "text/html", JsonRequestBehavior.AllowGet));
            }
        }
        static void Main(string[] args)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);
            AutoResetEvent idleEvent = new AutoResetEvent(false);

            var wfparams = new Dictionary <string, object>()
            {
                { "MaxNumber", 100 }
            };

            // State Machine workflow implementation
            WorkflowApplication wfApp =
                new WorkflowApplication(new StateMachineNumberGuessWorkflow(), wfparams);

            // Flowchart workflow implementation
            //WorkflowApplication wfApp =
            //    new WorkflowApplication(new FlowchartNumberGuessWorkflow(), wfparams);

            // Sequential workflow implementation
            //WorkflowApplication wfApp =
            //    new WorkflowApplication(new SequentialNumberGuessWorkflow(), wfparams);

            wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                int Turns = Convert.ToInt32(e.Outputs["Turns"]);
                Console.WriteLine("Congratulations, you guessed the number in {0} turns.", Turns);

                syncEvent.Set();
            };

            wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
            {
                Console.WriteLine(e.Reason);
                syncEvent.Set();
            };

            wfApp.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
            {
                Console.WriteLine(e.UnhandledException.ToString());
                return(UnhandledExceptionAction.Terminate);
            };

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

            wfApp.Run();

            // Loop until the workflow completes.
            WaitHandle[] handles = new WaitHandle[] { syncEvent, idleEvent };
            while (WaitHandle.WaitAny(handles) != 0)
            {
                // Gather the user input and resume the bookmark.
                bool validEntry = false;
                while (!validEntry)
                {
                    int Guess;
                    if (!Int32.TryParse(Console.ReadLine(), out Guess))
                    {
                        Console.WriteLine("Please enter an integer.");
                    }
                    else
                    {
                        validEntry = true;
                        wfApp.ResumeBookmark("EnterGuess", Guess);
                    }
                }
            }
        }
Ejemplo n.º 28
0
 public void GuessCorrectNumber()
 {
     _wfApp.ResumeBookmark("EnterGuess", ActualGuess);
     Assert.True(_completedEvent.WaitOne(500));
     Assert.True(_isComplete);
 }
Ejemplo n.º 29
0
 private void btnBookmarkContinue_Click(object sender, EventArgs e)
 {
     workflowApplication.ResumeBookmark(this.textBookmarkName.Text, int.Parse(this.textBoxContinue.Text));
 }
Ejemplo n.º 30
0
        public void ResumeBookmark(int workflowToDoListID, int userID, List <string> exchangeParamLists)
        {
            Dictionary <string, object> exchangeParams = new Dictionary <string, object>();

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

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

            DynEntity workflowToDoEntity = GatewayFactory.Default.Find("WorkflowToDoList", workflowToDoListID);
            DynEntity workflowInstance   = null;

            if (workflowToDoEntity != null)
            {
                workflowInstance = GatewayFactory.Default.Find("WorkflowInstance", Convert.ToInt32(workflowToDoEntity["WorkflowInstanceID"]));
                string bookmarkName = workflowToDoEntity["BookmarkName"].ToString();
                if (workflowInstance != null)
                {
                    string definition = ExecuteScalar("select RuntimeDefinition from Workflow where WorkflowID = " + workflowToDoEntity["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;
                    }

                    if (workflowApplication != null)
                    {
                        if (workflowApplication.GetBookmarks().Count(p => p.BookmarkName == bookmarkName) == 1)
                        {
                            DynEntity workflowActivityInstance = GatewayFactory.Default.Find("WorkflowActivityInstance", Convert.ToInt32(workflowToDoEntity["WorkflowActivityInstanceID"]));
                            if (workflowActivityInstance != null)
                            {
                                foreach (string item in exchangeParamLists)
                                {
                                    string[] arg = item.Split('^');

                                    switch (arg[0])
                                    {
                                    case "Handler":
                                        workflowActivityInstance["Handler"] = arg[1];
                                        break;

                                    case "ObjType":
                                        workflowActivityInstance["ObjType"] = arg[1];
                                        break;

                                    case "ObjID":
                                        workflowActivityInstance["ObjID"] = arg[1];
                                        break;

                                    case "DetailID":
                                        workflowActivityInstance["DetailID"] = arg[1];
                                        break;

                                    case "Opinion":
                                        workflowActivityInstance["Opinion"] = arg[1];
                                        break;

                                    default:
                                        break;
                                    }
                                }
                                exchangeParams["Actor"] = userID;

                                workflowActivityInstance["State"]   = "已执行";
                                workflowActivityInstance["EndTime"] = DateTime.Now;

                                using (TransactionScope trans = new TransactionScope())
                                {
                                    GatewayFactory.Default.Save(workflowActivityInstance);
                                    GatewayFactory.Default.Delete("WorkflowToDoList", workflowToDoListID);

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

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

                                    workflowApplication.ResumeBookmark(bookmarkName, exchangeParams);
                                    trans.Complete();
                                }
                            }
                            else
                            {
                                throw new ApplicationException(string.Format("在工作流活动:{0} 不存在无法执行,请检查", workflowActivityInstance["WorkflowActivityInstanceName"], bookmarkName));
                            }
                        }
                        else
                        {
                            throw new ApplicationException(string.Format("在工作流实例{0}中找不到书签名为{1}的活动", workflowToDoEntity["WorkflowInstanceID"], bookmarkName));
                        }
                    }
                    else
                    {
                        throw new ApplicationException("工作流创建实例失败!");
                    }
                }
            }
            else
            {
                throw new ApplicationException("当前待做任务在数据库中不存在,请检查!");
            }
        }