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)
        {
            var process = new WorkflowApplication(new Process());
            process.Run();

            System.Console.ReadKey();
        }
Beispiel #3
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 #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);
        }
Beispiel #6
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));
            }
        }
Beispiel #7
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 #8
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");
        }
Beispiel #9
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);
            }
        }
        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);
        }
    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 #12
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);
        }
Beispiel #13
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();
            }
        }
Beispiel #14
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();
        }
Beispiel #15
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 #16
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 #17
0
        public static IDictionary<String, Object> Invoke(Activity activity, IDictionary<String, Object> inputParameters = null, object[] extensions = null)
        {
            if (inputParameters == null)
            {
                inputParameters = new Dictionary<String, Object>();
            }

            WorkflowApplication application = new WorkflowApplication(activity, inputParameters);
            
            if (extensions != null)
            {
                foreach (var ext in extensions)
                {
                    application.Extensions.Add(ext);
                }
            }

            Exception thrownException = null;
            IDictionary<String, Object> outputParameters = new Dictionary<String, Object>();
            ManualResetEvent waitHandle = new ManualResetEvent(false);

            application.OnUnhandledException = (WorkflowApplicationUnhandledExceptionEventArgs arg) =>
            {
                // Preserve the stack trace in this exception
                // This is a hack into the Exception.InternalPreserveStackTrace method that allows us to re-throw and preserve the call stack
                _preserveStackTraceMethod.Invoke(arg.UnhandledException, null);

                thrownException = arg.UnhandledException;

                return UnhandledExceptionAction.Terminate;
            };
            application.Completed = (WorkflowApplicationCompletedEventArgs obj) =>
            {
                waitHandle.Set();

                outputParameters = obj.Outputs;
            };
            application.Aborted = (WorkflowApplicationAbortedEventArgs obj) => waitHandle.Set();
            application.Idle = (WorkflowApplicationIdleEventArgs obj) => waitHandle.Set();
            application.PersistableIdle = (WorkflowApplicationIdleEventArgs arg) =>
            {
                waitHandle.Set();

                return PersistableIdleAction.Persist;
            };
            application.Unloaded = (WorkflowApplicationEventArgs obj) => waitHandle.Set();

            application.Run();

            waitHandle.WaitOne();

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

            return outputParameters;
        }
    //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 #19
0
 static void Main(string[] args)
 {
     WorkflowApplication app = new WorkflowApplication(new Workflow1());
     app.Extensions.Add(new ConsoleSendEmail());
     //            app.Extensions.Add(new OutlookSendEmail());
     ManualResetEvent finished = new ManualResetEvent(false);
     app.Completed = (completedArgs) => { finished.Set(); };
     app.Run();
     finished.WaitOne();
 }
Beispiel #20
0
        static void Main(string[] args)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);
            AutoResetEvent idleEvent = new AutoResetEvent(false);
            Dictionary<string, object> input = new Dictionary<string, object> { { "MaxNumber", 100 } };

            WorkflowApplication app = new WorkflowApplication(new SequentialNumberGuessWorkflow(), input);

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

            app.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
            {
                Console.WriteLine(e.UnhandledException.ToString());
                syncEvent.Set();
                return UnhandledExceptionAction.Abort;
            };
            app.Idle = delegate(WorkflowApplicationIdleEventArgs e)
            {
                idleEvent.Set();
            };

            app.Run();

            // Loop until the workflow completes.
            WaitHandle[] handles = new WaitHandle[] { syncEvent, idleEvent };
            while (WaitHandle.WaitAny(handles) != 0)
            {
                // Gather the user input and resume the bookmark.
                bool validEntry = false;
                while (!validEntry)
                {
                    int Guess;
                    if (!Int32.TryParse(Console.ReadLine(), out Guess))
                    {
                        Console.WriteLine("Please enter an integer.");
                    }
                    else
                    {
                        validEntry = true;
                        app.ResumeBookmark("EnterGuess", Guess);
                    }
                }
            }
        }
Beispiel #21
0
    public void Run(string workflowPath)
    {
      Cursor.Current = Cursors.WaitCursor;

      Activity wf = (Activity)ActivityXamlServices.Load(workflowPath);

      WorkflowApplication wfApp = new WorkflowApplication(wf);

      Tracking sampleParticipant = new Tracking
      {
        TrackingProfile = new TrackingProfile()
        {
          Name = "CustomTrackingProfile",
          Queries = 
        {
           new ActivityStateQuery()
          {
              // Subscribe for track records from all activities for all states
              //ActivityName = "*"
              //ActivityStates.Closed
              ActivityName = "*",
              States = { ActivityStates.Closed },

              // Extract workflow variables and arguments as a part of the activity tracking record
              // VariableName = "*" allows for extraction of all variables in the scope
              // of the activity
              Variables = 
              {                                
                  { "*" }
              },
              Arguments = 
              {
                  { "*" }
              }
          }   
        }
        }

      };

      sampleParticipant.ActivityStateTracked += new Tracking.ActivityStateTrackedHandler(sampleParticipant_ActivityStateTracked);
      wfApp.Extensions.Add(sampleParticipant);

      if (Globals.ThisAddIn.CustomTaskPanes.Count > 0)
      {
          WorkflowActivitiesControl workflowActivities = Globals.ThisAddIn.CustomTaskPanes[0].Control as WorkflowActivitiesControl;
          workflowActivities.objectsTreeView.Nodes.Clear();
      }

      wfApp.Run();

      Cursor.Current = Cursors.Default;
    }
Beispiel #22
0
        public static void Start(Guid? instanceId)
        {
            var instance = new WorkflowApplication(new Workflow1());
            instance.PersistableIdle += OnPersistableIdle;
            instance.Completed += OnCompleted;
            instance.Idle += OnIdle;
            instance.Unloaded += OnUnloaded;

            // UNDONE: (maj) rather than using parameters, first check to see if there is an incomplete persisted file
            // and start from there
            if (!instanceId.HasValue)
            {
                instance.InstanceStore = new XmlWorkflowInstanceStore(instance.Id);
                instance.Run();
            }
            else
            {
                instance.InstanceStore = new XmlWorkflowInstanceStore(instanceId.Value);
                instance.Load(instanceId.Value);
                instance.Run();
            }
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            ManualResetEvent workflowCompleted = new ManualResetEvent(false);
            ManualResetEvent workflowIdled = new ManualResetEvent(false);

            Activity activity;

            using (Stream stream = File.OpenRead("Program.xaml"))
            {
                activity = ActivityXamlServices.Load(stream);
                stream.Close();
            }

            //create the WorkflowApplication using the Activity loaded from Program.xaml
            WorkflowApplication application = new WorkflowApplication(activity);

            //set up the Completed and Idle callbacks
            application.Completed = workflowCompletedEventArgs => workflowCompleted.Set();
            application.Idle = (e) =>
            {
                workflowIdled.Set();
            };

            //run the program
            application.Run();

            while (true)
            {
                string input = Console.ReadLine();

                workflowIdled.Reset();

                //provide the Console input to the Workflow
                application.ResumeBookmark("PromptBookmark", input);

                //wait for either the Idle or the Completion signal
                int signalled = WaitHandle.WaitAny(new WaitHandle[] { workflowCompleted, workflowIdled });

                //if completion was signalled, then we are done.
                if (signalled == 0)
                {
                    break;
                }
            }

            Console.WriteLine();
            Console.WriteLine("Press [ENTER] to exit.");

            Console.ReadLine();
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            Console.WriteLine(" --- Inicio de programa ---");

            _application = CreateNewWorkFlow();
            _application.Completed += OnCompleted;
            _application.InstanceStore = new XmlWorkflowInstanceStore();
            _application.Run();

            idleEvent.WaitOne();

            Console.WriteLine(" --- Fin de programa ---");
            Console.ReadLine();
        }
Beispiel #25
0
        static void RunWithWorkflowApplication(Activity workflow1, Dictionary<string, object> wfArgs) {
            AutoResetEvent waitHandle = new AutoResetEvent(false);
            WorkflowApplication app = new WorkflowApplication(workflow1, wfArgs);

            app.Completed = (completedArgs) => {
                waitHandle.Set();
                Console.WriteLine("Workflow done");
            };

            app.Run();

            waitHandle.WaitOne();
            Console.WriteLine("Done");
        }
Beispiel #26
0
 static void RunUnderApplication(Activity activity)
 {
     Application application = new System.Windows.Application() { ShutdownMode = ShutdownMode.OnExplicitShutdown };
     application.Startup += delegate
     {
         WorkflowApplication wfApp = new WorkflowApplication(activity);
         wfApp.SynchronizationContext = SynchronizationContext.Current;
         wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
         {
             application.Shutdown();
         };
         wfApp.Run();
     };
     application.Run();
 }
    private void GetReimbursementVoid(Guid id)
    {
        // Initialize Windows Workflow Foundation
          WorkflowApplication _wfApp = new WorkflowApplication(new ReimbursementRequest());

          SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["workflows"].ConnectionString);
          _wfApp.InstanceStore = store;
          _wfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs ex)
          {
               return PersistableIdleAction.Persist;
          };
          _wfApp.Run();
          _wfApp.Unload();
          Session["wfid"] = _wfApp.Id;
    }
Beispiel #28
0
        public void ShouldReturnWorkflowThread()
        {
            AutoResetEvent sync = new AutoResetEvent(false);
            Int32 actionThreadID = 0;
            IDictionary<string, object> output = null;

            WorkflowApplication workflowApp =
              new WorkflowApplication(
                   new SayHello()
                   {
                       UserName = "******"
                   });

            // Create an Action<T> using a lambda expression
            // To be invoked when the workflow completes
            workflowApp.Completed = (e) =>
            {
                output = e.Outputs;
                actionThreadID = Thread.CurrentThread.ManagedThreadId;

                // Signal the test thread the workflow is done
                sync.Set();
            };

            workflowApp.Run();

            // Wait for the sync event for 1 second
            sync.WaitOne(TimeSpan.FromSeconds(1));

            Assert.IsNotNull(output,
              "output not set, workflow may have timed out");

            Assert.IsTrue(output.ContainsKey("WorkflowThread"),
              "SayHello must contain an OutArgument named WorkflowThread");

            // Don't know for sure what it is yet
            var outarg = output["WorkflowThread"];

            Assert.IsInstanceOfType(outarg, typeof(Int32),
              "WorkflowThread must be of type Int32");

            Assert.AreNotEqual(0, outarg,
              "WorkflowThread must not be zero");

            Debug.WriteLine("Test thread is " +
                    Thread.CurrentThread.ManagedThreadId);
            Debug.WriteLine("Workflow thread is " + outarg.ToString());
        }
        /// <summary>
        /// 创建工作流
        /// </summary>
        /// <param name="parameters">传入的参数</param>
        /// <returns>获取工作流实例的Id值</returns>
        public string Create(IDictionary<string, object> parameters)
        {
            _instanceStore = new SqlWorkflowInstanceStore(connectionString);
            InstanceView view = _instanceStore.Execute
                (_instanceStore.CreateInstanceHandle(),
                new CreateWorkflowOwnerCommand(),
                TimeSpan.FromSeconds(30));
            _instanceStore.DefaultInstanceOwner = view.InstanceOwner;

            WorkflowApplication i = new WorkflowApplication(ActivityXamlServices.Load(path), parameters);
            i.InstanceStore = _instanceStore;
            i.PersistableIdle = (waiea) => PersistableIdleAction.Unload;
            i.Run();
            return i.Id.ToString();

        }
Beispiel #30
0
        public void DemoVanTracking()
        {
            var tracker = new TestTrackingParticipant();
            var application = new WorkflowApplication(new WriteLine { Text = "Hoi" });
            application.Extensions.Add(tracker);

            var ready = new AutoResetEvent(false);

            application.Run();
            application.Completed += (e) => ready.Set();

            ready.WaitOne();

            Assert.IsTrue(tracker.IsInvoked);
            Assert.IsTrue(tracker.Records.Any());
        }
Beispiel #31
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();
        }
        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();
        }
Beispiel #33
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 #34
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);
        }