Beispiel #1
0
        static void Interact(WorkflowApplication application)
        {
            IList<BookmarkInfo> bookmarks = application.GetBookmarks();

            while (true)
            {
                Console.Write("Bookmarks:");
                foreach (BookmarkInfo info in bookmarks)
                {
                    Console.Write(" '" + info.BookmarkName + "'");
                }
                Console.WriteLine();

                Console.WriteLine("Enter the name of the bookmark to resume");
                string bookmarkName = Console.ReadLine();

                if (bookmarkName != null && !bookmarkName.Equals(string.Empty))
                {
                    Console.WriteLine("Enter the payload for the bookmark '{0}'", bookmarkName);
                    string bookmarkPayload = Console.ReadLine();

                    BookmarkResumptionResult result = application.ResumeBookmark(bookmarkName, bookmarkPayload);
                    if (result == BookmarkResumptionResult.Success)
                    {
                        return;
                    }
                    else
                    {
                        Console.WriteLine("BookmarkResumptionResult: " + result);
                    }
                }
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            var connStr = @"Data Source=.\sqlexpress;Initial Catalog=WorkflowInstanceStore;Integrated Security=True;Pooling=False";
            SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(connStr);

            Workflow1 w = new Workflow1();

            //instanceStore.
            //IDictionary<string, object> xx=WorkflowInvoker.Invoke(new Workflow1());
            //ICollection<string> keys=xx.Keys;

            WorkflowApplication a = new WorkflowApplication(w);
            a.InstanceStore = instanceStore;
            a.GetBookmarks();
            //a.ResumeBookmark("Final State", new object());

            a.Run();
            //a.ResumeBookmark(

            //a.Persist();
            //a.Unload();
            //Guid id = a.Id;
            //WorkflowApplication b = new WorkflowApplication(w);
            //b.InstanceStore = instanceStore;
            //b.Load(id);
            //WorkflowApplication a=new WorkflowApplication(
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);

            WorkflowApplication myApplication = new WorkflowApplication(new Sequence1());

            myApplication.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                syncEvent.Set();
            };

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

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

            myApplication.Run();

            while (true)
            {
                if (myApplication.GetBookmarks().Count > 0)
                {
                    string bookmarkName = myApplication.GetBookmarks()[0].BookmarkName;
                    string input = Console.ReadLine().Trim();
                    myApplication.ResumeBookmark(bookmarkName, input);

                    // Exit out of this loop only when the user has entered a non-empty string.
                    if (!String.IsNullOrEmpty(input))
                    {
                        break;
                    }
                }
            }

            syncEvent.WaitOne();

            System.Console.WriteLine("The program has ended. Please press [ENTER] to exit...");
            System.Console.ReadLine();
        }
Beispiel #4
0
 // Returns true if the WorkflowApplication has any pending bookmark
 static bool HasPendingBookmarks(WorkflowApplication application)
 {
     try
     {
         return application.GetBookmarks().Count > 0;
     }
     catch (WorkflowApplicationCompletedException)
     {
         return false;
     }
 }
Beispiel #5
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(new GuessingGameWF());
            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.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
 private static Boolean IsBookmarkValid(WorkflowApplication wfApp, String bookmarkName)
 {
     Boolean result = false;
     var bookmarks = wfApp.GetBookmarks();
     if (bookmarks != null)
     {
         result =
             (from b in bookmarks
              where b.BookmarkName == bookmarkName
              select b).Any();
     }
     return result;
 }
        /// <summary>
        /// Runs this instance.
        /// </summary>
        public override void Run()
        {
            Trace.WriteLine("Starting processing of messages");
            // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
            this.Client.OnMessage(
                receivedMessage =>
                    {
                        try
                        {
                            this.resetEvent = new ManualResetEvent(false);
                            // Process the message
                            Trace.WriteLine(
                                "Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString());

                            // Name of workflow to trigger.
                            var workflowToTrigger = receivedMessage.Properties["workflowName"];
                            // Prepare input message for Workflow.
                            var channelData = new ChannelData { Payload = receivedMessage.GetBody<HostQueueMessage>() };
                            this.arrivedMessage = channelData.Payload;
                            // You can save the workflow xaml externally (usually database). See this.
                            var workflowXaml = File.ReadAllText($"{workflowToTrigger}.txt");
                            if (!string.IsNullOrWhiteSpace(workflowXaml))
                            {
                                //// 5. Compose WF Application.
                                var workflowApplication =
                                    new WorkflowApplication(
                                        Routines.CreateWorkflowActivityFromXaml(workflowXaml, this.GetType().Assembly),
                                        new Dictionary<string, object> { { "ChannelData", channelData } });

                                //// 6. Extract Request Identifier to set it as identifier of workflow.
                                this.SetupWorkflowEnvironment(
                                    workflowApplication,
                                    channelData.Payload.WorkflowIdentifier);

                                //// 7. Test whether this is a resumed bookmark or a fresh message.
                                if (channelData.Payload.IsBookmark)
                                {
                                    //// 8.1. Make sure there is data for this request identifier in storage to avoid errors due to transient errors.
                                    if (null
                                        != this.repository.GetById(
                                            "WorkflowInstanceStoreData",
                                            channelData.Payload.WorkflowIdentifier.ToString()))
                                    {
                                        //// Prepare a new workflow instance as we need to resume bookmark.
                                        var bookmarkedWorkflowApplication =
                                            new WorkflowApplication(
                                                Routines.CreateWorkflowActivityFromXaml(
                                                    workflowXaml,
                                                    this.GetType().Assembly));
                                        this.SetupWorkflowEnvironment(
                                            bookmarkedWorkflowApplication,
                                            channelData.Payload.WorkflowIdentifier);

                                        //// 9. Resume bookmark and supply input as is from channel data.
                                        bookmarkedWorkflowApplication.Load(channelData.Payload.WorkflowIdentifier);

                                        //// 9.1. If workflow got successfully completed, remove the host message.
                                        if (BookmarkResumptionResult.Success
                                            == bookmarkedWorkflowApplication.ResumeBookmark(
                                                bookmarkedWorkflowApplication.GetBookmarks().Single().BookmarkName,
                                                channelData,
                                                TimeSpan.FromDays(7)))
                                        {
                                            Trace.Write(
                                                Routines.FormatStringInvariantCulture("Bookmark successfully resumed."));
                                            this.resetEvent.WaitOne();
                                            this.Client.Complete(receivedMessage.LockToken);
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        //// This was a transient error.
                                        Trace.Write(Routines.FormatStringInvariantCulture("Error"));
                                    }
                                }

                                //// 10. Run workflow in case of normal execution.
                                workflowApplication.Run(TimeSpan.FromDays(7));
                                Trace.Write(
                                    Routines.FormatStringInvariantCulture(
                                        "Workflow for request id has started execution"));
                                this.resetEvent.WaitOne();
                            }
                        }
                        catch
                        {
                            // Handle any message processing specific exceptions here
                        }
                    });

            this.CompletedEvent.WaitOne();
        }
    //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();
        }
    }
Beispiel #9
0
        private TResponse ContinueWorkflow_todelete <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.ResumeBookmark;

            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();
                    this.WorkflowId = (wfApp.InstanceStore as IStoreCorrelation).Correlation.CorrelationId;
                    wfApp.Load(this.WorkflowId, 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);
        }
Beispiel #10
0
        static void testOffline()
        {
            SESampleProcess2 p2 = new SESampleProcess2();
            //SESampleWorkFlow p2 = new SESampleWorkFlow();
            WorkflowApplication app = new WorkflowApplication(p2);
            AutoResetEvent rre = new AutoResetEvent(false);
            app.Idle = (e) =>
            {
                rre.Set();
            };
            //TrackingProfile trackingProfile = new TrackingProfile();

            ////trackingProfile.Queries.Add(new WorkflowInstanceQuery

            ////{

            ////    States = { "*"}

            ////});

            ////trackingProfile.Queries.Add(new ActivityStateQuery

            ////{

            ////    States = {"*" }

            ////});

            //trackingProfile.Queries.Add(new CustomTrackingQuery

            //{

            //   ActivityName="*",

            //   Name = "*"

            //});
            //SETrackingParticipant p = new SETrackingParticipant();
            //p.TrackingProfile = trackingProfile;
            //app.Extensions.Add(p);

            app.Completed = (e) =>
            {
                Console.WriteLine("shit");
            };
            ReadOnlyCollection<BookmarkInfo> bookmarks = null;

            //bookmarks = app.GetBookmarks();
            //rre.WaitOne();
            WorkflowInstanceExtensionManager extensions = app.Extensions;

            BookmarkResumptionResult result;

            //result= app.ResumeBookmark("ProcessStart", new ChooseTransitionResult());
            //rre.WaitOne();
            //bookmarks = app.GetBookmarks();

            app.Run();

            rre.WaitOne();
            bookmarks = app.GetBookmarks();

            result = app.ResumeBookmark("RequireMoreInformation", new ChooseTransitionResult());
            rre.WaitOne();
            bookmarks = app.GetBookmarks();
            //app.Run();

            result = app.ResumeBookmark("ProvideMoreInformation", new ChooseTransitionResult());
            rre.WaitOne();
            bookmarks = app.GetBookmarks();

            result = app.ResumeBookmark("AssignToInvestigation", new ChooseTransitionResult());
            rre.WaitOne();
            bookmarks = app.GetBookmarks();

            result = app.ResumeBookmark("AssignToTriage", new ChooseTransitionResult());
            rre.WaitOne();
            bookmarks = app.GetBookmarks();

            result = app.ResumeBookmark("FinishProcess", new ChooseTransitionResult());
            rre.WaitOne();
            bookmarks = app.GetBookmarks();

            // ChooseTransitionResult rslt=new ChooseTransitionResult();
            //// rslt.ChooseResult="Not Need";
            // result=app.ResumeBookmark("AssignToTriage", rslt);
            // rre.WaitOne();
            // result = app.ResumeBookmark("FinishProcess", rslt);
            // rre.WaitOne();

            bookmarks = app.GetBookmarks();

            Console.WriteLine();
        }