Beispiel #1
1
        static void Main(string[] args)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);
            IDictionary<string, object> input = new Dictionary<string, object>()
            {
                {"Number1", 123},
                {"Number2", 456}
            };

            IDictionary<string, object> output = null;

            WorkflowApplication wfApp = new WorkflowApplication(new Workflow1(), input);
            wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                Console.WriteLine("Workflow thread id:" + Thread.CurrentThread.ManagedThreadId);
                output = e.Outputs;
                syncEvent.Set();
            };

            wfApp.Run();
            syncEvent.WaitOne();
            Console.WriteLine(output["Result"].ToString());
            Console.WriteLine("Host thread id:" + Thread.CurrentThread.ManagedThreadId);

            WorkflowInvoker.Invoke(new Workflow1());
            Console.WriteLine("Presione una letra para continuar...");
            Console.ReadKey();
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            WorkflowApplication wfApplication = new WorkflowApplication(new Activity1());

            SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["ZhuangBPM"].ToString());
            wfApplication.InstanceStore = instanceStore;


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


            wfApplication.PersistableIdle = (e) => {
                System.Console.WriteLine("persistableIdle:{0}", e.InstanceId); 

                return PersistableIdleAction.Unload;
            };

            wfApplication.Run();



            Console.ReadKey();
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            var process = new WorkflowApplication(new Process());
            process.Run();

            System.Console.ReadKey();
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);

            // create the workflow app and add handlers for the Idle and Completed actions
            WorkflowApplication app = new WorkflowApplication(new Sequence1());
            app.Idle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                syncEvent.Set();
            };
            app.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                syncEvent.Set();
            };

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

            // read some text from the console and resume the readText bookmark (created in the first WaitForInput activity)
            string text = Console.ReadLine();
            app.ResumeBookmark("readText", text);
            syncEvent.WaitOne();

            // read some text from the console, convert it to number, and resume the readNumber bookmark (created in the second WaitForInput activity)
            int number = ReadNumberFromConsole();
            app.ResumeBookmark("readNumber", number);
            syncEvent.WaitOne();

            Console.WriteLine("");
            Console.WriteLine("Press [ENTER] to exit...");
            Console.ReadLine();
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            _event = new AutoResetEvent(false);
            bool more = true;
            int result = 0;
            var activity = new AccumulatorActivity();
            var accumulator = new WorkflowApplication(activity);
            accumulator.Completed = new Action<WorkflowApplicationCompletedEventArgs>((e) =>
            {
                result = (int)e.Outputs["Sum"];
                more = false;
                _event.Set();
            });
            accumulator.Extensions.Add(new Notification(NotifySum));
            accumulator.Run();

            while (more)
            {
                Console.Write("Enter number: ");
                int number = int.Parse(Console.ReadLine());
                accumulator.ResumeBookmark("GetNumber", number);
                _event.WaitOne();
            }

            Console.WriteLine("Result is " + result);
        }
        protected override void LoadAndExecute()
        {
            MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(this.workflowDesigner.Text));
            DynamicActivity workflowToRun = ActivityXamlServices.Load(ms) as DynamicActivity;

            WorkflowInspectionServices.CacheMetadata(workflowToRun);

            this.workflowApplication = new WorkflowApplication(workflowToRun);

            this.workflowApplication.Extensions.Add(this.output);

            this.workflowApplication.Completed = this.WorkflowCompleted;
            this.workflowApplication.OnUnhandledException = this.WorkflowUnhandledException;
            this.workflowApplication.Aborted = this.WorkflowAborted;

            this.workflowApplication.Extensions.Add(this.InitialiseVisualTrackingParticipant(workflowToRun));

            try
            {
                this.running = true;
                this.workflowApplication.Run();
            }
            catch (Exception e)
            {
                this.output.WriteLine(ExceptionHelper.FormatStackTrace(e));
                StatusViewModel.SetStatusText(Resources.ExceptionInDebugStatus, this.workflowName);
            }
        }
        public static WorkflowApplication createInstance(string xamlString, Dictionary<string, object> dictionary, TrackingParticipant tracking)
        {
            WorkflowApplication instance = null;

            DynamicActivity dynamicActivity = tool.activityByXaml(xamlString) as DynamicActivity;

            if (dictionary != null)
            {
                instance = new WorkflowApplication(dynamicActivity, dictionary);
            }
            else
            {
                instance = new WorkflowApplication(dynamicActivity);
            }

            instance.Aborted = aborted;
            instance.Completed = completed;
            instance.OnUnhandledException = onUnhandledException;
            instance.PersistableIdle = persistableIdle;
            instance.Unloaded = unloaded;

            if (tracking != null)
            {
                instance.Extensions.Add(tracking);
            }

            return instance;
        }
Beispiel #8
0
        protected override void StartInternal()
        {
            DynamicActivity activity;

            using (var stream = new MemoryStream(Encoding.Default.GetBytes(WorkflowDesigner.Text)))
            {
                activity = ActivityXamlServices.Load(stream) as DynamicActivity;
            }

            if (activity == null)
            {
                return;
            }

            WorkflowInspectionServices.CacheMetadata(activity);

            workflowApplication = new WorkflowApplication(activity);

            workflowApplication.Extensions.Add(OutputWriter);
            workflowApplication.Extensions.Add(InitialiseVisualTrackingParticipant(activity));

            workflowApplication.Completed += Completed;
            workflowApplication.OnUnhandledException += OnUnhandledException;
            workflowApplication.Aborted += Aborted;

            try
            {
                workflowApplication.Run();
                OnRunningStateChanged(new WorkflowExecutingStateEventArgs(true));
            }
            catch (Exception e)
            {
                OutputWriter.WriteLine(e.StackTrace);
            }
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            TrackingProfile fileTrackingProfile = new TrackingProfile();
            fileTrackingProfile.Queries.Add(new WorkflowInstanceQuery
            {
                States = { "*" }
            });

            fileTrackingProfile.Queries.Add(new ActivityStateQuery()
            {
                States = {
                    ActivityStates.Executing,
                    ActivityStates.Closed
                }
            });

            FileTrackingParticipant fileTrackingParticipant = new FileTrackingParticipant();
            fileTrackingParticipant.TrackingProfile = fileTrackingProfile;

            AutoResetEvent waitHandler = new AutoResetEvent(false);
            WorkflowApplication wfapp = new WorkflowApplication(new Workflow1());
            wfapp.Unloaded = (wfAppEventArg) => { waitHandler.Set(); };
            wfapp.Extensions.Add(fileTrackingParticipant);
            wfapp.Run();

            waitHandler.WaitOne();
        }
 public static void RunCheckCheck(Guid id, ReviewCheckCheck Form)
 {
     SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(@"server=.\SQLEXPRESS;database=aspnetdb;uid=sa;pwd=123456");
     WorkflowApplication application2 = new WorkflowApplication(new DocumentPublish());
     application2.InstanceStore = instanceStore;
     application2.Completed = (workflowApplicationCompletedEventArgs) =>
     {
         Console.WriteLine("\nWorkflowApplication has Completed in the {0} state.", workflowApplicationCompletedEventArgs.CompletionState);
         instanceUnloaded.Set();
     };
     application2.PersistableIdle = (e) =>
     {
         instanceUnloaded.Set();
         return PersistableIdleAction.Unload;
     };
     application2.Unloaded = (workflowApplicationEventArgs) =>
     {
         Console.WriteLine("WorkflowApplication has Unloaded\n");
         instanceUnloaded.Set();
     };
     application2.Load(id);
     application2.ResumeBookmark("WaitCheckingChecking", Form);
     instanceUnloaded.WaitOne();
     Console.ReadLine();
 }
Beispiel #11
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 #12
0
        /*
         * Enable Analytic and Debug Logs:
         * Event Viewer -> Applications and Services Logs ->
         * Microsoft -> Windows -> Application Server-Applications
         * Right-click "Application Server-Applications" -> select View ->
         * Show Analytic and Debug Logs -> Refresh
         * */
        static void Main(string[] args)
        {
            //Tracking Configuration
            TrackingProfile trackingProfile = new TrackingProfile();
            trackingProfile.Queries.Add(new WorkflowInstanceQuery
            {
                States = { "*" }
            });
            trackingProfile.Queries.Add(new ActivityStateQuery
            {
                States = { "*" }
            });
            trackingProfile.Queries.Add(new CustomTrackingQuery
            {
                ActivityName = "*",
                Name = "*"
            });
            EtwTrackingParticipant etwTrackingParticipant =
                new EtwTrackingParticipant();
            etwTrackingParticipant.TrackingProfile = trackingProfile;

            // Run workflow app "Workflow1.xaml"
            AutoResetEvent waitHandler = new AutoResetEvent(false);
            WorkflowApplication wfApp =
                new WorkflowApplication(new Workflow1());
            wfApp.Completed = (arg) => { waitHandler.Set(); };
            wfApp.Extensions.Add(etwTrackingParticipant);
            wfApp.Run();
            waitHandler.WaitOne();
        }
Beispiel #13
0
        public override void Start()
        {
            if (IsRunning)
            {
                return;
            }

            using (var stream = new MemoryStream(Encoding.Default.GetBytes(Xaml)))
            {
                workflowApplication = new WorkflowApplication(ActivityXamlServices.Load(stream));
            }

            workflowApplication.Extensions.Add(OutputWriter);

            workflowApplication.Completed += OnWorkflowCompleted;
            workflowApplication.Aborted += OnWorkflowAborted;
            workflowApplication.OnUnhandledException += OnWorkflowUnhandledException;

            try
            {
                OnExecutingStateChanged(new WorkflowExecutingStateEventArgs(true));
                workflowApplication.Run();
            }
            catch (Exception e)
            {
                OutputWriter.WriteLine(e.StackTrace);
                OnExecutingStateChanged(new WorkflowExecutingStateEventArgs(false));
            }
        }
        // creates a workflow application, binds parameters, links extensions and run it
        public WorkflowApplication CreateAndRun(RequestForProposal rfp)
        {
            // input parameters for the WF program
            IDictionary<string, object> inputs = new Dictionary<string, object>();
            inputs.Add("Rfp", rfp);

            // create and run the WF instance
            Activity wf = new PurchaseProcessWorkflow();
            WorkflowApplication instance = new WorkflowApplication(wf, inputs);
            XmlWorkflowInstanceStore store = new XmlWorkflowInstanceStore(instance.Id);
            instance.InstanceStore = store;
            instance.PersistableIdle += OnIdleAndPersistable;
            instance.Completed += OnWorkflowCompleted;
            instance.Idle += OnIdle;

            //Create the persistence Participant and add it to the workflow instance
            XmlPersistenceParticipant xmlPersistenceParticipant = new XmlPersistenceParticipant(instance.Id);
            instance.Extensions.Add(xmlPersistenceParticipant);

            // add a tracking participant
            instance.Extensions.Add(new SaveAllEventsToTestFileTrackingParticipant());

            // add instance to the host list of running instances
            this.instances.Add(instance.Id, instance);

            // continue executing this instance
            instance.Run();

            return instance;
        }
Beispiel #15
0
        private static void Main(string[] args)
        {
            const int workflowCompleted = 0;
            const int workflowIdle = 1;

            var syncEvents = new[]
                                 {
                                     new AutoResetEvent(false),
                                     new AutoResetEvent(false),
                                 };
            var wfApp = new WorkflowApplication(new TestReadLine());
            string bookmarkName = string.Empty;
            bool workflowComplete = false;

            // Signal the main thread we are done
            wfApp.Completed = (e) => syncEvents[workflowCompleted].Set();

            // When the host detects an idle
            wfApp.Idle = (e) =>
                             {
                                 // Search the bookmarks
                                 foreach (
                                     var bi in
                                         e.Bookmarks.Where(
                                             bi => bi.BookmarkName == "FirstName" || bi.BookmarkName == "LastName"))
                                 {
                                     Console.WriteLine("Found bookmark {0}", bi.BookmarkName);
                                     // For FirstName or LastName bookmarks prompt with a readline
                                     bookmarkName = bi.BookmarkName;
                                     syncEvents[workflowIdle].Set();
                                 }
                             };

            wfApp.Run();

            while (!workflowComplete)
            {
                // Wait for events
                switch (WaitHandle.WaitAny(syncEvents, TimeSpan.FromSeconds(5)))
                {
                    case WaitHandle.WaitTimeout:
                        Console.WriteLine("Sorry you took too long");
                        wfApp.Terminate("Timeout");
                        break;

                    case workflowCompleted:
                        workflowComplete = true;
                        break;

                    case workflowIdle:
                        Console.WriteLine("Reading response for bookmark {0}", bookmarkName);
                        // Resume with the response from the user
                        wfApp.ResumeBookmark(bookmarkName, Console.ReadLine());
                        break;
                }
            }

            Console.WriteLine("Sample Completed - press any key to exit");
            Console.ReadKey(true);
        }
        private static void ProcessHandler(int userId)
        {
            //获取待处理的流程
            DbContext dbcontext = new DbContext();
            var       lst       = dbcontext.FlowInfo.Where(x => x.RowState == RowStates.正常)
                                  .Where(x => x.HandlerId == userId)
                                  .ToList();

            if (lst.Count <= 0)
            {
                Console.WriteLine("没有待处理的流程");
                return;
            }
            int indexTMP = 0;

            lst.ForEach(x => Console.WriteLine(string.Format("索引:{0},流程ID:{1},处理人ID:{2},处理人:{3},表单:{4}",
                                                             indexTMP++, x.WFInstanceId, x.HandlerId, x.HandlerName, x.FlowContext)));
            Console.WriteLine("请输入流程索引");
            int index = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("请输入审批意见");
            Console.WriteLine(string.Format("{0}---{1}", (int)HandlerOptions.意, HandlerOptions.意.ToString()));
            Console.WriteLine(string.Format("{0}---{1}", (int)HandlerOptions.驳回, HandlerOptions.驳回.ToString()));
            HandlerOptions opt = (HandlerOptions)Convert.ToInt32(Console.ReadLine());
            //组织表单数据
            var formData = Newtonsoft.Json.Linq.JObject.Parse(lst[index].FlowContext);

            formData["HandlerOption"] = Newtonsoft.Json.Linq.JToken.FromObject(opt);//demo,这个键写死
            //启动流程
            System.Activities.WorkflowApplication wfa = new System.Activities.WorkflowApplication(new LeaveFlow());
            InitWF(wfa);
            wfa.Load(lst[index].WFInstanceId);
            wfa.ResumeBookmark(lst[index].BookmarkName, formData);
        }
        public void AnyActivityInstanceStateFindsClosed()
        {
            // Arrange
            var activity = new AddToNumOrThrow();
            dynamic args = new WorkflowArguments();
            args.Num = 2;
            var host = new WorkflowApplication(activity, args);
            var tracking = new ListTrackingParticipant();
            host.Extensions.Add(tracking);

            try
            {
                host.RunEpisode();

                // Act
                var any = tracking.Records.Any(ActivityInstanceState.Closed);

                // Assert
                Assert.IsTrue(any);
            }
            finally
            {
                tracking.Trace();
            }
        }
Beispiel #18
0
        // resume execution of a workflow instance
        static void RunWorkflow(WorkflowApplication application, AutoResetEvent resetEvent)
        {
            application.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                Console.WriteLine("Workflow completed in state " + e.CompletionState);

                if (e.TerminationException != null)
                {
                    Console.WriteLine("Termination exception: " + e.TerminationException);
                }

                Console.WriteLine("-------------------------------");
                Console.WriteLine("- Input has been written to {0}\\out.txt", Environment.CurrentDirectory);
                Console.WriteLine("-------------------------------");

                resetEvent.Set();
            };
            application.Unloaded = delegate(WorkflowApplicationEventArgs e)
            {
                Console.WriteLine("Workflow unloaded");
                resetEvent.Set();
            };

            application.Run();
        }
Beispiel #19
0
        // single interaction with the user. The user enters a string in the console and that
        // string is used to resume the ReadLine activity bookmark
        static void Interact(WorkflowApplication application, AutoResetEvent resetEvent)
        {
            Console.WriteLine("Workflow is ready for input");
            Console.WriteLine("Special commands: 'unload', 'exit'");

            bool done = false;
            while (!done)
            {
                Console.Write("> ");
                string s = Console.ReadLine();
                if (s.Equals("unload"))
                {
                    try
                    {
                        // attempt to unload will fail if the workflow is idle within a NoPersistZone
                        application.Unload(TimeSpan.FromSeconds(5));
                        done = true;
                    }
                    catch (TimeoutException e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                else if (s.Equals("exit"))
                {
                    application.ResumeBookmark("inputBookmark", s);
                    done = true;
                }
                else
                {
                    application.ResumeBookmark("inputBookmark", s);
                }
            }
            resetEvent.WaitOne();
        }
 /// <summary>
 /// Adds a new WorkflowApplication to the cache
 /// </summary>
 /// <param name="application">
 /// The application. 
 /// </param>
 /// <returns>
 /// The WorkflowApplication that was added or updated 
 /// </returns>
 public WorkflowApplication Add(WorkflowApplication application)
 {
     Debug.Assert(this.dictionary != null, "dictionary != null");
     var observer = new WorkflowApplicationObserver(application) { Aborted = this.Aborted };
     return this.dictionary.AddOrUpdate(
         application.Id, guid => application, (guid, workflowApplication) => application);
 }
        public void WorkflowArgumentsCanPassToWorkflowApplication()
        {
            // Arrange
            var activity = new ArgTest();
            dynamic input = new WorkflowArguments();
            dynamic output = null;
            var completed = new AutoResetEvent(false);
            // Act
            input.Num1 = 2;
            input.Num2 = 3;

            var host = new WorkflowApplication(activity, input);
            host.Completed += args =>
                {
                    output = WorkflowArguments.FromDictionary(args.Outputs);
                    completed.Set();
                };

            host.Run();

            // Wait for complete
            Assert.IsTrue(completed.WaitOne(1000));

            // Assert
            Assert.AreEqual(5, output.Result);
        }
Beispiel #22
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 #23
0
        static void Main(string[] args)
        {
            Console.WriteLine("***** Welcome to this amazing WF application *****");

            // Get data from user, to pass to workflow.
            Console.Write("Please enter the data to pass the workflow: ");
            string wfData = Console.ReadLine();

            // Package up the data as a dictionary.
            Dictionary<string, object> wfArgs = new Dictionary<string, object>();
            wfArgs.Add("MessageToShow", wfData);

            // Used to inform primary thread to wait!
            AutoResetEvent waitHandle = new AutoResetEvent(false);

            // Pass to the workflow.
            WorkflowApplication app = new WorkflowApplication(new Workflow1(), wfArgs);

            // Hook up an event with this app.
            // When I’m done, notifiy other thread I’m done,
            // and print a message.
            app.Completed = (completedArgs) =>
            {
                waitHandle.Set();
                Console.WriteLine("The workflow is done!");
            };

            // Start the workflow!
            app.Run();

            // Wait until I am notified the workflow is done.
            waitHandle.WaitOne();

            Console.WriteLine("Thanks for playing");
        }
        public void Run()
        {
            this.workflowDesigner.Flush();
            MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(this.workflowDesigner.Text));

            DynamicActivity activityToRun = ActivityXamlServices.Load(ms) as DynamicActivity;

            this.workflowApplication = new WorkflowApplication(activityToRun);

            this.workflowApplication.Extensions.Add(this.output);
            this.workflowApplication.Completed = this.WorkflowCompleted;
            this.workflowApplication.Aborted = this.WorkflowAborted;
            this.workflowApplication.OnUnhandledException = this.WorkflowUnhandledException;
            StatusViewModel.SetStatusText(Resources.RunningStatus, this.workflowName);

            try
            {
                this.running = true;
                this.workflowApplication.Run();
            }
            catch (Exception e)
            {
                this.output.WriteLine(ExceptionHelper.FormatStackTrace(e));
                StatusViewModel.SetStatusText(Resources.ExceptionStatus, this.workflowName);
                this.running = false;
            }
        }
Beispiel #25
0
        static void LoadAndCompleteInstance()
        {
            string input = Console.ReadLine();

            WorkflowApplication application = new WorkflowApplication(activity);
            application.InstanceStore = instanceStore;

            application.Completed = (workflowApplicationCompletedEventArgs) =>
            {
                Console.WriteLine("\nWorkflowApplication has Completed in the {0} state.", workflowApplicationCompletedEventArgs.CompletionState);
            };

            application.Unloaded = (workflowApplicationEventArgs) =>
            {
                Console.WriteLine("WorkflowApplication has Unloaded\n");
                instanceUnloaded.Set();
            };

            application.Load(id);

            //this resumes the bookmark setup by readline
            application.ResumeBookmark(readLineBookmark, input);

            instanceUnloaded.WaitOne();
        }
    protected void Button1_Click(object sender, EventArgs e)

    {
     
           //设置参数
            Dictionary<string,object> para=new  Dictionary<string, object>();
            CrowdTask task = new CrowdTask(TextBox1.Text,TextBox2.Text);
            para.Add("task", task);

            //启动工作流
           WorkflowApplication crowdsourcing = new WorkflowApplication(new mainTask1(),para);
           task.taskType= TaskType.mainTask;
           crowdsourcing.Run();
           task.taskWorkflowId = crowdsourcing.Id.ToString();
           try
           {
               crowdTaskService = new CrowdTaskService();
               int result = crowdTaskService.insert(task);
               if(result==1){
                   //插入成功,保存对应的工作流实例
                   MyWorkflowInstance.setWorkflowApplication(crowdsourcing.Id.ToString(),crowdsourcing);
                   crowdTaskService.mainTaskSetCrowdTaskMainTaskIdByWorkflowId(crowdsourcing.Id.ToString());
                   Server.Transfer("viewMyTask.aspx?workflowId=" + task.taskWorkflowId);
               }
           }
           catch (Exception exception)
           {
               throw exception ;
           }
          
        
    }
Beispiel #27
0
        static void Run()
        {
            AutoResetEvent applicationUnloaded = new AutoResetEvent(false);
            WorkflowApplication application = new WorkflowApplication(workflow);
            application.InstanceStore = instanceStore;
            SetupApplication(application, applicationUnloaded);

            StepCountExtension stepCountExtension = new StepCountExtension();
            application.Extensions.Add(stepCountExtension);

            application.Run();
            Guid id = application.Id;
            applicationUnloaded.WaitOne();

            while (stepCountExtension.CurrentCount < totalSteps)
            {
                application = new WorkflowApplication(workflow);
                application.InstanceStore = instanceStore;
                SetupApplication(application, applicationUnloaded);

                stepCountExtension = new StepCountExtension();
                application.Extensions.Add(stepCountExtension);
                application.Load(id);

                string input = Console.ReadLine();

                application.ResumeBookmark(echoPromptBookmark, input);
                applicationUnloaded.WaitOne();
            }
        }
 internal WorkflowApplicationUnhandledExceptionEventArgs(WorkflowApplication application, Exception exception, Activity exceptionSource, string exceptionSourceInstanceId)
     : base(application)
 {
     this.UnhandledException = exception;
     this.ExceptionSource = exceptionSource;
     this.ExceptionSourceInstanceId = exceptionSourceInstanceId;
 }
Beispiel #29
0
        /// <summary>
        /// 第一步,统一入口,各种流程,请假流程,采购流程,调薪流程,
        /// </summary>
        /// <returns></returns>
        private static HzWorkFlowContext StartAppliaction()
        {
            System.Xaml.XamlXmlReaderSettings st = new System.Xaml.XamlXmlReaderSettings()
            {
                LocalAssembly = System.Reflection.Assembly.GetExecutingAssembly()
            };
            System.Activities.Activity act = null;
            using (var reader = new System.Xaml.XamlXmlReader(workflowName, st)) {
                act = System.Activities.XamlIntegration.ActivityXamlServices.Load(reader);
            }
            HzWorkFlowContext context = new HzWorkFlowContext();

            context.CreateDateTime = DateTime.Now;
            context.Creator        = "eeroom";
            //formdata由页面表单json提交而来,这里只是为了测试
            context.FormData = Newtonsoft.Json.JsonConvert.SerializeObject(new QinJiaFormdata()
            {
                Category = 3,
                Days     = 5
            });
            var dict = new Dictionary <string, object>();

            //对应活动的入参
            dict.Add("hzWorkFlowContext", context);
            var wfa = new System.Activities.WorkflowApplication(act, dict);

            ConfigWfa(wfa);
            wfa.Run();
            return(context);
        }
Beispiel #30
0
        public WorkflowService(
            IUsersService users

          )
        {
            _users = users;
            T = NullLocalizer.Instance;
            Logger = NullLogger.Instance;
            SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(_users.ApplicationConnectionString);
            _wfApp = new WorkflowApplication(new XODB.Workflow.AssignResponsibility());
            _wfApp.InstanceStore = store;
            
            XName wfHostTypeName = XName.Get("XODB", _users.ApplicationID.ToString());
            Dictionary<XName, object> wfScope = new Dictionary<XName, object> { { workflowHostTypePropertyName, wfHostTypeName } };
            _wfApp.AddInitialInstanceValues(wfScope);
            
            _wfApp.Extensions.Add(new ResponsibilityExtension());
            List<XName> variantProperties = new List<XName>() 
            { 
                ResponsibilityExtension.xNS.GetName("CompanyID"), 
                ResponsibilityExtension.xNS.GetName("ContactID") 
            };
            store.Promote("Responsibility", variantProperties, null);

            InstanceHandle handle = store.CreateInstanceHandle(null);
            var cmd = new CreateWorkflowOwnerCommand
            {
                InstanceOwnerMetadata =
                    {
                        {workflowHostTypePropertyName, new InstanceValue(wfHostTypeName)}
                    }
            };
            InstanceOwner owner = store.Execute(handle, cmd, TimeSpan.MaxValue).InstanceOwner;
            store.DefaultInstanceOwner = owner;
            
            handle.Free();
   
            _wfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                return PersistableIdleAction.Persist;
            };

            _wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    foreach (var item in e.Outputs)
                    {
                        System.Diagnostics.Debug.WriteLine("Variable:{0} has value: {1}", item.Key, item.Value);
                    }
                }
            };

            var trackingParticipant = new TrackingHelper.DebugTrackingParticipant
            {
                TrackingProfile = TrackingHelper.SimpleProfile
            };
            _wfApp.Extensions.Add(trackingParticipant);
        }
 internal WorkflowApplicationCompletedEventArgs(WorkflowApplication application, Exception terminationException, ActivityInstanceState completionState, IDictionary<string, object> outputs)
     : base(application)
 {
     Fx.Assert(ActivityUtilities.IsCompletedState(completionState), "event should only fire for completed activities");
     this.terminationException = terminationException;
     this.completionState = completionState;
     this.outputs = outputs;
 }
    //end
    protected void btnEdit_ServerClick(object sender, EventArgs e)
    {
        if (((this.txtName.Value.Length == 0) || (this.uploadurl.Value.Length == 0)) || (this.selWorkFlow.SelectedValue.Length == 0))
        {
            MessageBox.Show(this, "请您填写完整的信息");
        }
        else
        {
            Model.SelectRecord selectRecord = new Model.SelectRecord("WorkFlow", "", "*", "where id='" + this.selWorkFlow.SelectedValue + "'");
            DataTable table = BLL.SelectRecord.SelectRecordData(selectRecord).Tables[0];
            string content = File.ReadAllText(System.Web.HttpContext.Current.Request.MapPath("../") + table.Rows[0]["URL"].ToString());

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

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

            if (BLL.Document.DocumentUpdate(documents) == 1)
            {
                UserOperatingManager.InputUserOperating(this.Session["admin"].ToString(), "工作流管理", "编辑工作流" + documents.Name + "的信息成功");
                MessageBox.ShowAndRedirect(this, "编辑公文成功!", "/document/DocumentList.aspx");
            }
            else
            {
                UserOperatingManager.InputUserOperating(this.Session["admin"].ToString(), "工作流管理", "编辑工作流" + documents.Name + "的信息失败");
                MessageBox.Show(this, "编辑工作流失败");
            }
        }
    }
Beispiel #33
0
        //第一步以后,后续所有流程步骤的入口
        private static void ApproveOp(bool op, Guid workflowId, HzWorkFlowContext hzwfContext)
        {
            System.Xaml.XamlXmlReaderSettings st = new System.Xaml.XamlXmlReaderSettings()
            {
                LocalAssembly = System.Reflection.Assembly.GetExecutingAssembly()
            };
            System.Activities.Activity act = null;
            using (var reader = new System.Xaml.XamlXmlReader(workflowName, st)) {
                act = System.Activities.XamlIntegration.ActivityXamlServices.Load(reader);
            }
            var wfa = new System.Activities.WorkflowApplication(act);

            ConfigWfa(wfa);
            wfa.Load(workflowId);
            wfa.ResumeBookmark(bookmark, op);
        }
Beispiel #34
0
            public static Dictionary <XName, InstanceValue> GenerateInitialData(WorkflowApplication instance)
            {
                var data = new Dictionary <XName, InstanceValue>(10);

                data[WorkflowNamespace.Bookmarks]  = new InstanceValue(instance.Controller.GetBookmarks(), InstanceValueOptions.WriteOnly | InstanceValueOptions.Optional);
                data[WorkflowNamespace.LastUpdate] = new InstanceValue(DateTime.UtcNow, InstanceValueOptions.WriteOnly | InstanceValueOptions.Optional);

                foreach (var mappedVariable in instance.Controller.GetMappedVariables())
                {
                    data[WorkflowNamespace.VariablesPath.GetName(mappedVariable.Key)] = new InstanceValue(mappedVariable.Value, InstanceValueOptions.WriteOnly | InstanceValueOptions.Optional);
                }

                Fx.AssertAndThrow(instance.Controller.State != WorkflowInstanceState.Aborted, "Cannot generate data for an aborted instance.");
                if (instance.Controller.State != WorkflowInstanceState.Complete)
                {
                    data[WorkflowNamespace.Workflow] = new InstanceValue(instance.Controller.PrepareForSerialization());
                    data[WorkflowNamespace.Status]   = new InstanceValue(instance.Controller.State == WorkflowInstanceState.Idle ? "Idle" : "Executing", InstanceValueOptions.WriteOnly);
                }
                else
                {
                    data[WorkflowNamespace.Workflow] = new InstanceValue(instance.Controller.PrepareForSerialization(), InstanceValueOptions.Optional);
                    var completionState = instance.Controller.GetCompletionState(out var outputs, out var completionException);

                    if (completionState == ActivityInstanceState.Faulted)
                    {
                        data[WorkflowNamespace.Status]    = new InstanceValue("Faulted", InstanceValueOptions.WriteOnly);
                        data[WorkflowNamespace.Exception] = new InstanceValue(completionException, InstanceValueOptions.WriteOnly | InstanceValueOptions.Optional);
                    }
                    else if (completionState == ActivityInstanceState.Closed)
                    {
                        data[WorkflowNamespace.Status] = new InstanceValue("Closed", InstanceValueOptions.WriteOnly);
                        if (outputs != null)
                        {
                            foreach (var output in outputs)
                            {
                                data[WorkflowNamespace.OutputPath.GetName(output.Key)] = new InstanceValue(output.Value, InstanceValueOptions.WriteOnly | InstanceValueOptions.Optional);
                            }
                        }
                    }
                    else
                    {
                        Fx.AssertAndThrow(completionState == ActivityInstanceState.Canceled, "Cannot be executing when WorkflowState was completed.");
                        data[WorkflowNamespace.Status] = new InstanceValue("Canceled", InstanceValueOptions.WriteOnly);
                    }
                }
                return(data);
            }
Beispiel #35
0
            /// <summary>
            /// Runs the specified instance.
            /// </summary>
            /// <param name="instance">The instance.</param>
            /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
            public bool Run(WorkflowApplication instance)
            {
                IAsyncResult?result = null;

                if (instance.Controller.HasPendingTrackingRecords)
                {
                    instance.EventData.NextCallback = this.Stage1Callback;
                    result = instance.Controller.BeginFlushTrackingRecords(ActivityDefaults.TrackingTimeout, EventFrameCallback, instance.EventData);

                    if (!result.CompletedSynchronously)
                    {
                        return(false);
                    }
                }

                return(this.OnStage1Complete(result, instance, true));
            }
Beispiel #36
0
            public LoadAsyncResult(WorkflowApplication application, PersistenceManager persistenceManager,
                                   IDictionary <XName, InstanceValue> values,

                                   DynamicUpdateMap updateMap,

                                   TimeSpan timeout,
                                   AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.application        = application;
                this.persistenceManager = persistenceManager;
                this.values             = values;
                this.timeoutHelper      = new TimeoutHelper(timeout);

                this.updateMap = updateMap;

                this.Initialize();
            }
        private static void Start(int userId, string userName)
        {
            DbContext dbcontext = new DbContext();
            FlowInfo  fl        = new FlowInfo()
            {
                Id                  = DateTime.Now.Ticks,
                CreatedTime         = DateTime.Now,
                CreatorId           = userId,
                CreatorName         = userName,
                FlowGroupName       = "开始",
                FlowNo              = Guid.NewGuid(),
                FlowNoParent        = Guid.Empty,
                FlowResult          = FlowResults.None,
                FlowState           = FlowStates.未提交,
                HandlerId           = userId,
                HandlerName         = userName,
                HandlerOption       = HandlerOptions.新建,
                NodeType            = NodeTypes.单人审批,
                HandlerTime         = DateTime.Now,
                PreviousHandlerId   = -1,
                PreviousHandlerName = string.Empty,
                PreviousHandlerTime = DateTime.Now,
                RowState            = RowStates.正常,
                WFInstanceId        = Guid.Empty,
            };

            LeaveInput input = new LeaveInput();

            Console.WriteLine("请输入请假的小时数");
            input.Hours = int.Parse(Console.ReadLine());
            Console.WriteLine("请输入请假理由");
            input.Remark   = Console.ReadLine();
            fl.FlowContext = Newtonsoft.Json.JsonConvert.SerializeObject(input);

            Dictionary <string, object> dict = new Dictionary <string, object>();

            dict.Add("flowInfo", fl);
            System.Activities.WorkflowApplication wfa = new System.Activities.WorkflowApplication(new LeaveFlow(), dict);
            fl.WFInstanceId = wfa.Id;
            InitWF(wfa);
            dbcontext.FlowInfo.Add(fl);
            dbcontext.SaveChanges();
            wfa.Run();
        }
            public bool Run(WorkflowApplication instance)
            {
                IAsyncResult result = null;

                if (instance.Controller.TrackingEnabled)
                {
                    instance.Controller.Track(new WorkflowInstanceRecord(instance.Id, instance.WorkflowDefinition.DisplayName, WorkflowInstanceStates.Idle, instance.DefinitionIdentity));

                    instance.EventData.NextCallback = this.Stage1Callback;
                    result = instance.Controller.BeginFlushTrackingRecords(ActivityDefaults.TrackingTimeout, EventFrameCallback, instance.EventData);

                    if (!result.CompletedSynchronously)
                    {
                        return(false);
                    }
                }

                return(this.OnStage1Complete(result, instance, true));
            }
Beispiel #39
0
        private static IDictionary <string, object> Invoke(Activity workflow, TimeSpan timeout, WorkflowInstanceExtensionManager extensions)
        {
            if (workflow == null)
            {
                throw FxTrace.Exception.ArgumentNull(nameof(workflow));
            }

            TimeoutHelper.ThrowIfNegativeArgument(timeout);

            var outputs = WorkflowApplication.Invoke(workflow, null, extensions, timeout);

            if (outputs == null)
            {
                return(ActivityUtilities.EmptyParameters);
            }
            else
            {
                return(outputs);
            }
        }
Beispiel #40
0
            public bool Run(WorkflowApplication instance, Exception exception, Activity exceptionSource, string exceptionSourceInstanceId)
            {
                IAsyncResult result = null;

                if (instance.Controller.HasPendingTrackingRecords)
                {
                    instance.EventData.NextCallback                     = this.Stage1Callback;
                    instance.EventData.UnhandledException               = exception;
                    instance.EventData.UnhandledExceptionSource         = exceptionSource;
                    instance.EventData.UnhandledExceptionSourceInstance = exceptionSourceInstanceId;
                    result = instance.Controller.BeginFlushTrackingRecords(ActivityDefaults.TrackingTimeout, EventFrameCallback, instance.EventData);

                    if (!result.CompletedSynchronously)
                    {
                        return(false);
                    }
                }

                return(this.OnStage1Complete(result, instance, exception, exceptionSource, exceptionSourceInstanceId));
            }
Beispiel #41
0
        private Guid correlate(WorkflowApplication wfApp)
        {
            //TODO: da completare
            if (wfApp.InstanceStore is IStoreCorrelation)
            {
                var scorrelation = (wfApp.InstanceStore as IStoreCorrelation);

                //if (scorrelation.Correlation != null
                //    && scorrelation.Correlation.WorkflowId != Guid.Empty)
                //{
                //    return scorrelation.Correlation.WorkflowId;
                //}
                //else if(scorrelation.Correlation != null
                //    && scorrelation.Correlation.CorrelationId != Guid.Empty
                //    && scorrelation.Correlation.WorkflowId == Guid.Empty)
                //{
                //    return scorrelation.Correlation.WorkflowId;
                //}
            }

            return(Guid.Empty);
        }
Beispiel #42
0
        private void InternalInvokeAsync(IDictionary <string, object> inputs, TimeSpan timeout, object userState)
        {
            var context = new AsyncInvokeContext(userState, this);

            if (userState != null)
            {
                AddToPendingInvokes(context);
            }
            Exception error = null;
            var       completedSynchronously = false;

            try
            {
                if (invokeCallback == null)
                {
                    invokeCallback = Fx.ThunkCallback(new AsyncCallback(InvokeCallback));
                }
                context.Operation.OperationStarted();
                var result = WorkflowApplication.BeginInvoke(this.workflow, inputs, this.extensions, timeout, SynchronizationContext.Current, context, invokeCallback, context);
                if (result.CompletedSynchronously)
                {
                    context.Outputs        = this.EndInvoke(result);
                    completedSynchronously = true;
                }
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }
                error = e;
            }
            if (error != null || completedSynchronously)
            {
                PostInvokeCompletedAndRemove(context, error);
            }
        }
            /// <summary>
            /// Initializes a new instance of the <see cref="InvokeAsyncResult"/> class.
            /// </summary>
            /// <param name="activity">The activity.</param>
            /// <param name="inputs">The inputs.</param>
            /// <param name="extensions">The extensions.</param>
            /// <param name="timeout">The timeout.</param>
            /// <param name="syncContext">The synchronize context.</param>
            /// <param name="invokeContext">The invoke context.</param>
            /// <param name="callback">The callback.</param>
            /// <param name="state">The state.</param>
            public InvokeAsyncResult(
                Activity activity,
                IDictionary <string, object> inputs,
                WorkflowInstanceExtensionManager extensions,
                TimeSpan timeout,
                SynchronizationContext syncContext,
                AsyncInvokeContext invokeContext,
                AsyncCallback callback,
                object state)
                : base(callback, state)
            {
                if (activity == null)
                {
                    throw new ArgumentNullException(nameof(activity));
                }

                this.completionWaiter = new AsyncWaitHandle();
                syncContext ??= SynchronousSynchronizationContext.Value;

                this.instance = WorkflowApplication.StartInvoke(activity, inputs, extensions, syncContext, new Action(this.OnInvokeComplete), invokeContext);

                if (this.completionWaiter.WaitAsync(WaitCompleteCallback, this, timeout))
                {
                    var completeSelf = this.OnWorkflowCompletion();

                    if (completeSelf)
                    {
                        if (this.completionException != null)
                        {
                            throw FxTrace.Exception.AsError(this.completionException);
                        }
                        else
                        {
                            this.Complete(true);
                        }
                    }
                }
            }
Beispiel #44
0
 private RunAsyncResult(WorkflowApplication instance, bool isUserRun, AsyncCallback callback, object state)
     : base(instance, callback, state) => this.isUserRun = isUserRun;
Beispiel #45
0
 private bool OnStage1Complete(IAsyncResult lastResult, WorkflowApplication instance, bool isStillSync) => this.OnStage1Complete(lastResult, instance, instance.EventData.UnhandledException, instance.EventData.UnhandledExceptionSource, instance.EventData.UnhandledExceptionSourceInstance);
Beispiel #46
0
        private void setWFEvents(WorkflowApplication wf)
        {
            wf.Idle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                Console.WriteLine("Workflow idled");
                s_idleEvent.Set();
                //s_syncEvent.Set();
            };

            wf.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                Console.WriteLine("Workflow completed with state {0}.", e.CompletionState.ToString());

                if (e.TerminationException != null)
                {
                    exception = e.TerminationException;
                    Console.WriteLine("TerminationException = {0}; {1}", e.TerminationException.GetType().ToString(), e.TerminationException.Message);
                }
                s_completedEvent?.Set();
                //s_syncEvent.Set();

                invokeMode = WorkflowInvokeMode.None;
            };

            wf.Unloaded = delegate(WorkflowApplicationEventArgs e)
            {
                Console.WriteLine("Workflow unloaded");
                if (this.invokeMode == WorkflowInvokeMode.Run)
                {
                    this.invokeMode = WorkflowInvokeMode.ResumeBookmark;
                }
                else
                {
                    this.invokeMode = WorkflowInvokeMode.None;
                }

                s_unloadedEvent.Set();
                //s_syncEvent.Set();
            };


            wf.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                if (instanceStore != null)
                {
                    return(PersistableIdleAction.Unload);
                }

                return(PersistableIdleAction.None);
            };

            wf.Aborted = e =>
            {
                this.exception = e.Reason;
                //throw e.Reason;

                //syncEvent.Set();
                s_syncEvent?.Set();
            };
            //wfApp.Idle = e => { /*syncEvent.Set();*/ };
            //wfApp.PersistableIdle = e => { return PersistableIdleAction.Unload; };
            //wfApp.OnUnhandledException = e => { return UnhandledExceptionAction.Terminate; };
        }
            private bool OnStage1Complete(IAsyncResult lastResult, WorkflowApplication application, bool isStillSync)
            {
                if (lastResult != null)
                {
                    application.Controller.EndFlushTrackingRecords(lastResult);
                }

                IAsyncResult result = null;

                if (application.RaiseIdleEvent())
                {
                    if (application.Controller.IsPersistable && application.persistenceManager != null)
                    {
                        var persistableIdleHandler = application.PersistableIdle;

                        if (persistableIdleHandler != null)
                        {
                            var action = PersistableIdleAction.None;

                            application.handlerThreadId = Thread.CurrentThread.ManagedThreadId;

                            try
                            {
                                application.isInHandler = true;
                                action = persistableIdleHandler(new WorkflowApplicationIdleEventArgs(application));
                            }
                            finally
                            {
                                application.isInHandler = false;
                            }

                            if (TD.WorkflowApplicationPersistableIdleIsEnabled())
                            {
                                TD.WorkflowApplicationPersistableIdle(application.Id.ToString(), action.ToString());
                            }

                            if (action != PersistableIdleAction.None)
                            {
                                var operation = PersistenceOperation.Unload;

                                if (action == PersistableIdleAction.Persist)
                                {
                                    operation = PersistenceOperation.Save;
                                }
                                else if (action != PersistableIdleAction.Unload)
                                {
                                    throw FxTrace.Exception.AsError(new InvalidOperationException(SR.InvalidIdleAction));
                                }

                                application.EventData.NextCallback = this.Stage2Callback;
                                result = application.BeginInternalPersist(operation, ActivityDefaults.InternalSaveTimeout, true, EventFrameCallback, application.EventData);

                                if (!result.CompletedSynchronously)
                                {
                                    return(false);
                                }
                            }
                        }
                        else
                        {
                            // Trace the default action
                            if (TD.WorkflowApplicationPersistableIdleIsEnabled())
                            {
                                TD.WorkflowApplicationPersistableIdle(application.Id.ToString(), PersistableIdleAction.None.ToString());
                            }
                        }
                    }
                }

                return(this.OnStage2Complete(result, application, isStillSync));
            }
 public void EndAbandon(IAsyncResult asyncResult)
 {
     WorkflowApplication.EndDiscardInstance(asyncResult);
 }
 public override bool CanRun(WorkflowApplication instance) => (this.ActionId != instance.actionCount && instance.Controller.State == WorkflowInstanceState.Idle) || instance.Controller.State == WorkflowInstanceState.Complete;
 internal WorkflowApplicationIdleEventArgs(WorkflowApplication application)
     : base(application)
 {
 }
Beispiel #51
0
        private IAsyncResult BeginInvoke(Activity workflow, TimeSpan timeout, WorkflowInstanceExtensionManager extensions, AsyncCallback callback, object state)
        {
            TimeoutHelper.ThrowIfNegativeArgument(timeout);

            return(WorkflowApplication.BeginInvoke(workflow, null, extensions, timeout, null, null, callback, state));
        }
Beispiel #52
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 #53
0
        public void createApp(Activity activity)
        {
            //var xh = new XamlHelper(workflow.xaml);
            //extraextension.updateProfile(xh.Variables.ToArray(), xh.ArgumentNames.ToArray());
            TrackingParticipant = new WorkflowTrackingParticipant();
            TrackingParticipant.OnVisualTracking += Participant_OnVisualTracking;

            if (string.IsNullOrEmpty(InstanceId))
            {
                // Remove unknown Parameters, if we don't the workflow will fail
                foreach (var param in Parameters.ToList())
                {
                    var allowed = Workflow.Parameters.Where(x => x.name == param.Key).FirstOrDefault();
                    if (allowed == null || allowed.direction == workflowparameterdirection.@out)
                    {
                        Parameters.Remove(param.Key);
                    }
                }
                // Ensure Type
                foreach (var wfparam in Workflow.Parameters)
                {
                    if (Parameters.ContainsKey(wfparam.name) && wfparam.type == "System.Int32")
                    {
                        if (Parameters[wfparam.name] != null)
                        {
                            Parameters[wfparam.name] = int.Parse(Parameters[wfparam.name].ToString());
                        }
                    }
                    else if (Parameters.ContainsKey(wfparam.name) && wfparam.type == "System.Boolean")
                    {
                        if (Parameters[wfparam.name] != null)
                        {
                            Parameters[wfparam.name] = bool.Parse(Parameters[wfparam.name].ToString());
                        }
                    }
                }
                wfApp = new System.Activities.WorkflowApplication(activity, Parameters);
                wfApp.Extensions.Add(TrackingParticipant);
                foreach (var t in Plugins.WorkflowExtensionsTypes)
                {
                    try
                    {
                        var ext = (ICustomWorkflowExtension)Activator.CreateInstance(t);
                        ext.Initialize(RobotInstance.instance, Workflow, this);
                        wfApp.Extensions.Add(ext);
                    }
                    catch (Exception ex)
                    {
                        Log.Error("error init " + t.Name + ": " + ex.ToString());
                    }
                }
                if (Workflow.Serializable)
                {
                    //if (Config.local.localstate)
                    //{
                    //    if (!System.IO.Directory.Exists(System.IO.Directory.GetCurrentDirectory() + "\\state")) System.IO.Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + "\\state");
                    //    wfApp.InstanceStore = new Store.XMLFileInstanceStore(System.IO.Directory.GetCurrentDirectory() + "\\state");
                    //}
                    //else
                    //{
                    //    wfApp.InstanceStore = new Store.OpenFlowInstanceStore();
                    //}
                    wfApp.InstanceStore = new Store.OpenFlowInstanceStore();
                }
                addwfApphandlers(wfApp);
            }
            else
            {
                wfApp = new System.Activities.WorkflowApplication(activity);
                wfApp.Extensions.Add(TrackingParticipant);
                foreach (var t in Plugins.WorkflowExtensionsTypes)
                {
                    try
                    {
                        var ext = (ICustomWorkflowExtension)Activator.CreateInstance(t);
                        ext.Initialize(RobotInstance.instance, Workflow, this);
                        wfApp.Extensions.Add(ext);
                    }
                    catch (Exception ex)
                    {
                        Log.Error("error init " + t.Name + ": " + ex.ToString());
                    }
                }

                addwfApphandlers(wfApp);
                if (Workflow.Serializable || !Workflow.Serializable)
                {
                    //if (Config.local.localstate)
                    //{
                    //    if (!System.IO.Directory.Exists(System.IO.Directory.GetCurrentDirectory() + "\\state")) System.IO.Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + "\\state");
                    //    wfApp.InstanceStore = new Store.XMLFileInstanceStore(System.IO.Directory.GetCurrentDirectory() + "\\state");
                    //}
                    //else
                    //{
                    //    wfApp.InstanceStore = new Store.OpenFlowInstanceStore();
                    //}
                    wfApp.InstanceStore = new Store.OpenFlowInstanceStore();
                }
                wfApp.Load(new Guid(InstanceId));
            }
            state = "loaded";
        }
Beispiel #54
0
 private CancelAsyncResult(WorkflowApplication instance, AsyncCallback callback, object state)
     : base(instance, callback, state)
 {
 }
Beispiel #55
0
        public TResponse Execute2 <TRequest, TResponse>(TRequest request)
        {
            resetEvents();

            Action <WorkflowApplication> setWFEvents = delegate(WorkflowApplication wf)
            {
                wf.Idle = delegate(WorkflowApplicationIdleEventArgs e)
                {
                    Console.WriteLine("Workflow idled");
                    s_idleEvent.Set();
                };

                wf.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
                {
                    Console.WriteLine("Workflow completed with state {0}.", e.CompletionState.ToString());

                    if (e.TerminationException != null)
                    {
                        Console.WriteLine("TerminationException = {0}; {1}", e.TerminationException.GetType().ToString(), e.TerminationException.Message);
                    }
                    s_completedEvent.Set();
                };

                wf.Unloaded = delegate(WorkflowApplicationEventArgs e)
                {
                    Console.WriteLine("Workflow unloaded");
                    s_unloadedEvent.Set();
                };

                wf.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e)
                {
                    if (instanceStore != null)
                    {
                        return(PersistableIdleAction.Unload);
                    }

                    return(PersistableIdleAction.None);
                };
            };

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

            TResponse respnse = default(TResponse);

            Dictionary <string, object> inputs = new Dictionary <string, object>();

            inputs.Add("Request", request);
            WorkflowApplication wfApp = new WorkflowApplication(this.workflow, inputs);

            setWFEvents(wfApp);

            wfApp.Run();

            waitOne();

            return(respnse);
        }
Beispiel #56
0
 internal WorkflowApplicationAbortedEventArgs(WorkflowApplication application, Exception reason)
     : base(application)
 {
     this.Reason = reason;
 }
Beispiel #57
0
 public virtual bool CanRun(WorkflowApplication instance) => true;
Beispiel #58
0
            public UnloadOrPersistAsyncResult(WorkflowApplication instance, TimeSpan timeout, PersistenceOperation operation,
                                              bool isWorkflowThread, bool isInternalPersist, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.instance          = instance;
                this.timeoutHelper     = new TimeoutHelper(timeout);
                this.operation         = operation;
                this.isInternalPersist = isInternalPersist;
                this.isUnloaded        = (operation == PersistenceOperation.Unload || operation == PersistenceOperation.Complete);

                this.OnCompleting = UnloadOrPersistAsyncResult.completeCallback;

                bool completeSelf;
                var  success = false;

                // Save off the current transaction in case we have an async operation before we end
                // up creating the WorkflowPersistenceContext and create it on another thread. Do a
                // blocking dependent clone that we will complete when we are completed.
                //
                // This will throw TransactionAbortedException by design, if the transaction is
                // already rolled back.
                var currentTransaction = Transaction.Current;

                if (currentTransaction != null)
                {
                    this.dependentTransaction = currentTransaction.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
                }

                try
                {
                    if (isWorkflowThread)
                    {
                        Fx.Assert(this.instance.Controller.IsPersistable, "The runtime won't schedule this work item unless we've passed the guard");

                        // We're an internal persistence on the workflow thread which means that we
                        // are passed the guard already, we have the lock, and we know we aren't detached.

                        completeSelf = this.InitializeProvider();
                        success      = true;
                    }
                    else
                    {
                        this.instanceOperation = new RequiresPersistenceOperation();
                        try
                        {
                            if (this.instance.WaitForTurnAsync(this.instanceOperation, this.timeoutHelper.RemainingTime(), waitCompleteCallback, this))
                            {
                                completeSelf = this.ValidateState();
                            }
                            else
                            {
                                completeSelf = false;
                            }
                            success = true;
                        }
                        finally
                        {
                            if (!success)
                            {
                                this.NotifyOperationComplete();
                            }
                        }
                    }
                }
                finally
                {
                    // If we had an exception, we need to complete the dependent transaction.
                    if (!success)
                    {
                        if (this.dependentTransaction != null)
                        {
                            this.dependentTransaction.Complete();
                        }
                    }
                }

                if (completeSelf)
                {
                    this.Complete(true);
                }
            }
 private TerminateAsyncResult(WorkflowApplication instance, Exception reason, AsyncCallback callback, object state)
     : base(instance, callback, state) => this.reason = reason;
 internal WorkflowApplicationEventArgs(WorkflowApplication application)
 {
     this.Owner = application;
 }