示例#1
0
        private void btnCreateSequentialWorkflow_Click(object sender, EventArgs e)
        {
            ConnectionStringSettings connectionStringSettings = cboConnectionString.SelectedItem as ConnectionStringSettings;

            if (connectionStringSettings == null)
            {
                MessageBox.Show("No connection string selected.", "WFTools Samples",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;
            }

            SampleWorkFlowRuntime workflowRuntime;

            if (this.loadedWorkflowRuntimes.ContainsKey(connectionStringSettings.Name))
            {
                workflowRuntime = this.loadedWorkflowRuntimes[connectionStringSettings.Name];
            }
            else
            {
                workflowRuntime = new SampleWorkFlowRuntime(connectionStringSettings);
                workflowRuntime.WorkflowTerminated          += new EventHandler <WorkflowTerminatedEventArgs>(workflowRuntime_WorkflowTerminated);
                workflowRuntime.ServicesExceptionNotHandled += new EventHandler <ServicesExceptionNotHandledEventArgs>(workflowRuntime_ServicesExceptionNotHandled);
                this.loadedWorkflowRuntimes.Add(connectionStringSettings.Name, workflowRuntime);
            }

            // create a new sequential workflow
            WorkflowInstance workflowInstance = workflowRuntime.CreateSequentialWorkflow();

            workflowInstance.Start();

            ManualWorkflowSchedulerService schedulerService = workflowRuntime.GetService <ManualWorkflowSchedulerService>();

            schedulerService.RunWorkflow(workflowInstance.InstanceId);
        }
示例#2
0
        public void StartWorkflow(Type workflowType, Dictionary <string, object> inparms, Guid caller, IComparable qn, ActivityExecutionContext context)
        {
            this.ParentId = caller;

            WorkflowRuntime wr = this.Runtime;

            CallContext.SetData(CallingWorkflowIDProperty.Name, caller);
            CallContext.SetData(CallingWorkflowQueueNameProperty.Name, qn);


            //wr.WorkflowCreated += new EventHandler<WorkflowEventArgs>(wr_WorkflowCreated);
            WorkflowInstance wi = wr.CreateWorkflow(workflowType, inparms);

            // wr.WorkflowCompleted += new EventHandler<WorkflowCompletedEventArgs>(wr_WorkflowCompleted);
            _childWorkflows.Add(wi.InstanceId, new ChildData(caller, qn));

            //SubWorkflowArgs arg = new SubWorkflowArgs(wi.InstanceId, wi.InstanceId, caller, null);
            //this.OnStartSubWorkflow(arg);

            wi.Start();


            //// Call Workflow Service when the SubWorkflow Started
            //WorkflowServices workflowServicde = context.GetService<WorkflowServices>();
            SubWorkflowArgs arg = new SubWorkflowArgs(wi.InstanceId, wi.InstanceId, caller, null);

            this.OnSubWorkflowInstanceStart(arg);
            //////////////////////
            ManualWorkflowSchedulerService ss = wr.GetService <ManualWorkflowSchedulerService>();

            if (ss != null)
            {
                ss.RunWorkflow(wi.InstanceId);
            }
        }
示例#3
0
        /// <summary>
        /// 创建工作流运行时
        /// </summary>
        /// <param name="IsPer">是否使用持久化</param>
        /// <returns></returns>
        public static WorkflowRuntime CreateWorkFlowRuntime(bool IsPer)
        {
            try
            {
                WorkflowRuntime WfRuntime = new WorkflowRuntime();


                if (IsPer)
                {
                    ConnectionStringSettings defaultConnectionString = ConfigurationManager.ConnectionStrings["OracleConnection"];
                    WfRuntime.AddService(new AdoPersistenceService(defaultConnectionString, true, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(0)));
                    WfRuntime.AddService(new AdoTrackingService(defaultConnectionString));
                    WfRuntime.AddService(new AdoWorkBatchService());
                }

                FlowEvent ExternalEvent = new FlowEvent();
                ExternalDataExchangeService objService = new ExternalDataExchangeService();
                WfRuntime.AddService(objService);
                objService.AddService(ExternalEvent);

                ManualWorkflowSchedulerService scheduleService = new ManualWorkflowSchedulerService();
                WfRuntime.AddService(scheduleService);

                TypeProvider typeProvider = new TypeProvider(null);
                WfRuntime.AddService(typeProvider);
                WfRuntime.StartRuntime();
                return(WfRuntime);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("CreateWorkFlowRuntime异常信息 :" + ex.ToString());
                throw new Exception(ex.Message);
            }
        }
示例#4
0
        /// <summary>
        /// Run the workflow in a synchronous way using the ManualWorkflowSchedulerService
        /// </summary>
        /// <param name="workflowInstanceId"></param>
        private void RunWorkFlow(Guid workflowInstanceId)
        {
            StateMachineWorkflowInstance stateMachine = new StateMachineWorkflowInstance(_workflowRuntime, workflowInstanceId);
            StateActivity oldState = stateMachine.CurrentState;

            ManualWorkflowSchedulerService service = _workflowRuntime.GetService <ManualWorkflowSchedulerService>();

            service.RunWorkflow(workflowInstanceId);

            // Hack : This is not the best way to handle exceptions (sychronously) in Workflows
            // Read more about the best practice here - http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=833203&SiteID=1
            // And here - http://www.topxml.com/rbnews/Orchestration---Workflow/re-60988_Synchronous-CallWorkflow-sample-revisited.aspx
            if (CallContext.GetData("Exception") != null)
            {
                // This is the compensation activity - that should be ideally defined in the workflow itself
                // In our case, the only activity that occurs after External Method Calls for Book, Cancel etc.
                // is the state change activity. We just reverse it here.
                // Ideally, we can have a fault handler for each event driven activity
                // that will set the call context with a "WCFException" and halt the execution of the workflow.
                stateMachine.SetState(oldState);

                service.RunWorkflow(workflowInstanceId);

                Exception exceptionToThrow = (Exception)CallContext.GetData("Exception");

                CallContext.SetData("Exception", null);

                throw exceptionToThrow;
            }
        }
示例#5
0
文件: MainForm.cs 项目: jjg0519/OA
        private void btnCreateSequentialWorkflow_Click(Object sender, EventArgs e)
        {
            ConnectionStringSettings persistenceConnectionString = cboPersistenceService.SelectedItem as ConnectionStringSettings;
            ConnectionStringSettings trackingConnectionString    = cboTrackingService.SelectedItem as ConnectionStringSettings;

            if (persistenceConnectionString == null)
            {
                MessageBox.Show("No connection string selected for persistence service.", "WFTools Samples",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;
            }

            String workflowRuntimeKey = String.Format("{0}_{1}_{2}",
                                                      persistenceConnectionString.Name,
                                                      trackingConnectionString == null ? "None" : trackingConnectionString.Name,
                                                      chkUseLocalTransactions.Checked);

            SampleWorkFlowRuntime workflowRuntime;

            if (!this.loadedWorkflowRuntimes.TryGetValue(workflowRuntimeKey, out workflowRuntime))
            {
                workflowRuntime = new SampleWorkFlowRuntime(persistenceConnectionString,
                                                            trackingConnectionString, chkUseLocalTransactions.Checked);

                workflowRuntime.WorkflowTerminated          += workflowRuntime_WorkflowTerminated;
                workflowRuntime.ServicesExceptionNotHandled += workflowRuntime_ServicesExceptionNotHandled;

                this.loadedWorkflowRuntimes.Add(workflowRuntimeKey, workflowRuntime);
            }

            // create a new sequential workflow
            WorkflowInstance workflowInstance = workflowRuntime.CreateSequentialWorkflow();

            if (chkModifyWorkflow.Checked)
            {
                Activity        rootActivity    = workflowInstance.GetWorkflowDefinition();
                WorkflowChanges workflowChanges = new WorkflowChanges(rootActivity);

                // modify the workflow
                Activity          activityToRemove = workflowChanges.TransientWorkflow.GetActivityByName("codeActivity3");
                CompositeActivity parentActivity   = activityToRemove.Parent;

                parentActivity.Activities.Remove(activityToRemove);

                CodeActivity codeActivity = new CodeActivity("TestChangeActivity");
                codeActivity.ExecuteCode +=
                    delegate { Trace.WriteLine("Test Change Activity executed..."); };

                parentActivity.Activities.Add(codeActivity);

                workflowInstance.ApplyWorkflowChanges(workflowChanges);
            }

            workflowInstance.Start();

            ManualWorkflowSchedulerService schedulerService = workflowRuntime.GetService <ManualWorkflowSchedulerService>();

            schedulerService.RunWorkflow(workflowInstance.InstanceId);
        }
示例#6
0
        public void Echo(string theString)
        {
            //Aquire the callback from the current OperationContext
            callback = OperationContext.Current.GetCallbackChannel <IEchoableCallback>();
            //grab the version of the incoming message in case we need to create a fault later
            version = OperationContext.Current.IncomingMessageVersion;

            Console.WriteLine("WCF: Got {0}", theString);

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

            parameters.Add("ReceivedData", theString);

            WorkflowRuntime workflowRuntime          = new WorkflowRuntime();
            ManualWorkflowSchedulerService scheduler = new ManualWorkflowSchedulerService();

            workflowRuntime.AddService(scheduler);
            workflowRuntime.StartRuntime();

            workflowRuntime.WorkflowCompleted  += this.OnWorkflowCompleted;
            workflowRuntime.WorkflowTerminated += this.OnWorkflowTerminated;

            WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(Workflow1), parameters);

            instance.Start();

            scheduler.RunWorkflow(instance.InstanceId);
        }
示例#7
0
        public void TestCleanup()
        {
            _workflowRuntime.StopRuntime();
            _workflowRuntime.Dispose();

            _workflowRuntime = null;
            _scheduler       = null;
            _dataExchange    = null;
        }
        public void Flush()
        {
            _workflowRuntime                = null;
            _externalDataExchangeService    = null;
            _manualWorkflowSchedulerService = null;
            _fileWorkflowPersistenceService = null;
            _formsWorkflowEventService      = null;

            _resourceLocker.ResetInitialization();
        }
示例#9
0
        public InvokerLocalService(WorkflowRuntime workflowRuntime)
        {
            if (workflowRuntime == null)
            {
                throw new ArgumentNullException("workflowRuntime");
            }

            this._workflowRuntime = workflowRuntime;
            this._scheduler       = workflowRuntime.GetService <ManualWorkflowSchedulerService>();
        }
示例#10
0
        static void Main(string[] args)
        {
            using (WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                String         wfResult   = String.Empty;
                AutoResetEvent waitHandle = new AutoResetEvent(false);

                workflowRuntime.WorkflowCompleted
                    += delegate(object sender, WorkflowCompletedEventArgs e)
                    {
                    //retrieve the output parameter value
                    if (e.OutputParameters.ContainsKey("Result"))
                    {
                        wfResult = (String)e.OutputParameters["Result"];
                        waitHandle.Set();
                    }
                    };

                //add the manual scheduler service prior to
                //starting the workflow runtime. Use the constructor
                //that allows us to set useActiveTimers to true.
                ManualWorkflowSchedulerService scheduler =
                    new ManualWorkflowSchedulerService(true);
                workflowRuntime.AddService(scheduler);
                //start the workflow runtime
                workflowRuntime.StartRuntime();

                //create a dictionary with input arguments
                Dictionary <String, Object> wfArguments
                    = new Dictionary <string, object>();
                wfArguments.Add("InputString", "one");

                //create the workflow instance
                WorkflowInstance instance = workflowRuntime.CreateWorkflow(
                    typeof(SharedWorkflows.Workflow1), wfArguments);
                //indicate that it should execute when we provide a thread
                instance.Start();

                //run the workflow instance synchronously on our thread
                scheduler.RunWorkflow(instance.InstanceId);

                //since the workflow contains a DelayActivity, the RunWorkflow
                //method will return immediately at the start of the delay.
                //use the waitHandle to signal the actual completion of
                //the workflow when the DelayActivity completes.
                waitHandle.WaitOne(7000, false);

                //display the workflow result
                Console.WriteLine(wfResult);

                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
            }
        }
示例#11
0
        /// <summary>
        /// Run the workflow with the given instance id on the current thread.
        /// </summary>
        /// <param name="instanceId"></param>
        /// <returns></returns>
        private bool RunWorkflow(Guid instanceId)
        {
            this.SetWorkflowQueueInfo(instanceId, this.ParentWorkflowId);
            ManualWorkflowSchedulerService scheduler = GetWorkflowSchedulerService();

            this.InitWorkflowEvents();
            bool result = scheduler.RunWorkflow(instanceId);

            this.DisposeWorkflowEvents();
            return(result);
        }
示例#12
0
        /// <summary>
        /// Runs a <see cref="WorkflowInstance" /> using the <see cref="ManualWorkflowSchedulerService" />
        /// with error handling support if available.
        /// </summary>
        /// <param name="instanceId">
        /// Unique identifier of a workflow instance.
        /// </param>
        /// <returns>
        /// <c>true</c> if the workflow is running, <c>false</c> otherwise.
        /// </returns>
        public Boolean RunWorkflow(Guid instanceId)
        {
            ManualWorkflowSchedulerService workflowScheduler = GetService <ManualWorkflowSchedulerService>();

            if (workflowScheduler == null)
            {
                // manual scheduler is not present, we do not need to
                // manually run the workflow
                return(true);
            }

            Exception workflowException = null;
            EventHandler <WorkflowTerminatedEventArgs> terminatedHandler = null;

            terminatedHandler =
                delegate(object sender, WorkflowTerminatedEventArgs e)
            {
                if (e.WorkflowInstance.InstanceId == instanceId && e.Exception != null)
                {
                    workflowRuntime.WorkflowTerminated -= terminatedHandler;
                    workflowException = e.Exception;
                }
            };

            workflowRuntime.WorkflowTerminated += terminatedHandler;

            ErrorHandlingService errorHandlingService = GetService <ErrorHandlingService>();

            if (errorHandlingService != null)
            {
                EventHandler <ErrorHandlingEventArgs> errorHandler = null;
                errorHandler =
                    delegate(object sender, ErrorHandlingEventArgs e)
                {
                    if (e.InstanceId == instanceId && e.Exception != null)
                    {
                        errorHandlingService.Error -= errorHandler;
                        workflowException           = e.Exception;
                    }
                };

                errorHandlingService.Error += errorHandler;
            }

            Boolean isRunning = workflowScheduler.RunWorkflow(instanceId);

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

            return(isRunning);
        }
示例#13
0
        public void ExecuteWorkflow(WorkflowRuntime workflowRuntime, Type workflowType, Dictionary <string, object> properties)
        {
            ManualWorkflowSchedulerService manualScheduler = workflowRuntime.GetService <ManualWorkflowSchedulerService>();

            WorkflowInstance instance = workflowRuntime.CreateWorkflow(workflowType, properties);

            instance.Start();
            var instanceId = instance.InstanceId;

            EventHandler <WorkflowCompletedEventArgs> completedHandler = null;

            completedHandler = delegate(object o, WorkflowCompletedEventArgs e)
            {
                if (e.WorkflowInstance.InstanceId == instanceId)
                {
                    // copy the output parameters in the specified properties dictionary
                    Dictionary <string, object> .Enumerator enumerator = e.OutputParameters.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        KeyValuePair <string, object> pair = enumerator.Current;
                        if (properties.ContainsKey(pair.Key))
                        {
                            properties[pair.Key] = pair.Value;
                        }
                    }
                }
            };

            Exception x = null;
            EventHandler <WorkflowTerminatedEventArgs> terminatedHandler = null;

            terminatedHandler = delegate(object o, WorkflowTerminatedEventArgs e)
            {
                if (e.WorkflowInstance.InstanceId == instanceId)
                {
                    x = e.Exception;
                    Debug.WriteLine(e.Exception);
                }
            };

            workflowRuntime.WorkflowCompleted  += completedHandler;
            workflowRuntime.WorkflowTerminated += terminatedHandler;

            manualScheduler.RunWorkflow(instance.InstanceId);

            workflowRuntime.WorkflowTerminated -= terminatedHandler;
            workflowRuntime.WorkflowCompleted  -= completedHandler;

            if (null != x)
            {
                throw new WorkflowException(x);
            }
        }
示例#14
0
        /// <summary>
        /// Runs the workflow.
        /// </summary>
        /// <param name="instance">The instance.</param>
        public static void RunWorkflow(WorkflowInstance instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            ManualWorkflowSchedulerService service = WorkflowRuntime.GetService <ManualWorkflowSchedulerService>();

            if (service != null)
            {
                service.RunWorkflow(instance.InstanceId);
            }
        }
示例#15
0
        public void TestInitialize()
        {
            _workflowRuntime = new WorkflowRuntime();
            _scheduler       = new ManualWorkflowSchedulerService();

            _workflowRuntime.AddService(_scheduler);
            _workflowRuntime.AddService(new ExternalDataExchangeService());

            _dataExchange = new MockDataExchange();
            _dataExchange.Reset();
            _workflowRuntime.GetService <ExternalDataExchangeService>().AddService(_dataExchange);

            _workflowRuntime.StartRuntime();
        }
示例#16
0
        /// <summary>
        /// Helper method used to manually execute an workflow instance whilst handling
        /// any exceptions that are thrown during execution.
        /// </summary>
        /// <param name="instanceId">
        /// <see cref="Guid" /> representing the workflow instance.
        /// </param>
        /// <param name="workflowRuntime">
        /// A <see cref="WorkflowRuntimeWrapperBase" /> which wraps the real <see cref="WorkflowRuntime" />.
        /// </param>
        /// <remarks>
        /// This method relies on an instance of the <see cref="ManualWorkflowSchedulerService" />
        /// as the thrown exception is handled synchrously.
        /// </remarks>
        public static void ManualRunWithErrorHandling(Guid instanceId, WorkflowRuntime workflowRuntime)
        {
            ManualWorkflowSchedulerService scheduler = workflowRuntime.GetService <ManualWorkflowSchedulerService>();

            if (scheduler == null)
            {
                throw new ArgumentException("No ManualWorkflowSchedulerService associated with this runtime.", "workflowRuntime");
            }

            Exception workflowException = null;
            EventHandler <WorkflowTerminatedEventArgs> terminatedHandler = null;

            terminatedHandler =
                delegate(object sender, WorkflowTerminatedEventArgs e)
            {
                if (e.WorkflowInstance.InstanceId == instanceId && e.Exception != null)
                {
                    workflowRuntime.WorkflowTerminated -= terminatedHandler;

                    workflowException = e.Exception;
                }
            };
            workflowRuntime.WorkflowTerminated += terminatedHandler;

            ErrorHandlingService errorHandlingService = workflowRuntime.GetService <ErrorHandlingService>();

            if (errorHandlingService != null)
            {
                EventHandler <ErrorHandlingEventArgs> errorHandler = null;
                errorHandler =
                    delegate(object sender, ErrorHandlingEventArgs e)
                {
                    if (e.InstanceId == instanceId && e.Exception != null)
                    {
                        errorHandlingService.Error -= errorHandler;

                        workflowException = e.Exception;
                    }
                };
                errorHandlingService.Error += errorHandler;
            }

            scheduler.RunWorkflow(instanceId);

            if (workflowException != null)
            {
                throw workflowException;
            }
        }
示例#17
0
        protected void ButtonRunWF_Click(object sender, EventArgs e)
        {
            WorkflowInstance instance = GlobalWorkflowRuntime.WorkflowRuntime.CreateWorkflow(typeof(SimpleWorkflow));

            instance.Start();

            //ViewState["WorkflowInstanceId"] = instance.InstanceId;

            ManualWorkflowSchedulerService service = GlobalWorkflowRuntime.WorkflowRuntime.GetService <ManualWorkflowSchedulerService>();

            if (service != null)
            {
                service.RunWorkflow(instance.InstanceId);
            }
        }
示例#18
0
        public void TestInitialize()
        {
            _workflowRuntime = new WorkflowRuntime();
            _scheduler       = new ManualWorkflowSchedulerService();
            _tracking        = new PropertyTrackingService();

            _workflowRuntime.AddService(_scheduler);
            _workflowRuntime.AddService(_tracking);
            _workflowRuntime.AddService(new ExternalDataExchangeService());

            _dataExchange = new MockDataExchange(Delay, 2 * Delay + Delay);
            _workflowRuntime.GetService <ExternalDataExchangeService>().AddService(_dataExchange);

            _workflowRuntime.StartRuntime();
        }
示例#19
0
        /// <summary>
        /// 激发事件到一下状态,并获取状态代码
        /// </summary>
        /// <param name="WfRuntime"></param>
        /// <param name="instance"></param>
        /// <param name="CurrentStateName"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static string GetNextStateByEvent(WorkflowRuntime WfRuntime, WorkflowInstance instance, string CurrentStateName, string xml)
        {
            try
            {
                if (!WfRuntime.IsStarted)
                {
                    WfRuntime.StartRuntime();
                }
                WfRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                {
                    instance = null;
                };
                StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(WfRuntime, instance.InstanceId);

                ManualWorkflowSchedulerService scheduleService = WfRuntime.GetService(typeof(ManualWorkflowSchedulerService)) as ManualWorkflowSchedulerService;
                scheduleService.RunWorkflow(workflowinstance.InstanceId);
                workflowinstance.SetState(CurrentStateName);

                FlowDataType.FlowData FlowData = new FlowDataType.FlowData();
                FlowData.xml = xml;

                scheduleService.RunWorkflow(instance.InstanceId);
                WfRuntime.GetService <FlowEvent>().OnDoFlow(instance.InstanceId, FlowData);//激发流程引擎流转到下一状态
                scheduleService.RunWorkflow(instance.InstanceId);
                //while (true)
                //{
                //    string stateName = workflowinstance.CurrentStateName;

                //    if (stateName != null && stateName.ToUpper().IndexOf("START") == -1)
                //    {
                //        break;
                //    }
                //}
                //System.Threading.Thread.Sleep(1000);
                if (instance == null)
                {
                    return("EndFlow");
                }
                StateMachineWorkflowInstance workflowinstance1 = new StateMachineWorkflowInstance(WfRuntime, instance.InstanceId);
                return(workflowinstance1.CurrentStateName);
                //return GetNextState(WfRuntime, instance, CurrentStateName);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("GetNextStateByEvent异常信息 :" + ex.ToString());
                throw new Exception(ex.Message);
            }
        }
示例#20
0
        public void ComponentsProvidedByConfiguration()
        {
            WorkflowRuntime  runtime  = _container.Resolve <WorkflowRuntime>();
            WorkflowInstance instance = runtime.CreateWorkflow(typeof(CreateNameWorkflow));

            instance.Start();

            ManualWorkflowSchedulerService scheduler = _container.Resolve <ManualWorkflowSchedulerService>();

            scheduler.RunWorkflow(instance.InstanceId);

            TestingExternalData testingExternalData = (TestingExternalData)_container.Resolve <ITestingExternalData>();

            Assert.AreEqual("You are \"{0} {1}\".", testingExternalData.FullNameFormat, "Format must have been provided by config");
            Assert.AreEqual("You are \"hello world\".", testingExternalData.MostRecentFullName, "Full name must have been set by workflow execution");
        }
示例#21
0
        public static WorkflowRuntime CreateDefaultRuntime()
        {
            WorkflowRuntime workflowRuntime = new WorkflowRuntime();

            var manualService = new ManualWorkflowSchedulerService();

            workflowRuntime.AddService(manualService);

            var syncCallService = new Activities.CallWorkflowService();

            workflowRuntime.AddService(syncCallService);

            workflowRuntime.StartRuntime();

            return(workflowRuntime);
        }
示例#22
0
        public void StartWorkflow(Type workflowType, Dictionary <string, object> inparms, Guid caller, IComparable qn)
        {
            WorkflowRuntime  wr = this.Runtime;
            WorkflowInstance wi = wr.CreateWorkflow(workflowType, inparms);

            wi.Start();

            var instanceId = wi.InstanceId;

            _WorkflowQueue[instanceId] = new WorkflowInfo {
                Caller = caller, qn = qn
            };

            ManualWorkflowSchedulerService ss = wr.GetService <ManualWorkflowSchedulerService>();

            if (ss != null)
            {
                ss.RunWorkflow(wi.InstanceId);
            }
        }
示例#23
0
    /// <summary>
    /// The calculate button was pressed
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCalculate_Click(object sender, EventArgs e)
    {
        //retrieve the workflow runtime
        WorkflowRuntime workflowRuntime
            = Application["WorkflowRuntime"] as WorkflowRuntime;
        //retrieve the scheduler that is used to execute workflows
        ManualWorkflowSchedulerService scheduler =
            workflowRuntime.GetService(
                typeof(ManualWorkflowSchedulerService))
            as ManualWorkflowSchedulerService;

        //handle the WorkflowCompleted event in order to
        //retrieve the output parameters from the completed workflow
        workflowRuntime.WorkflowCompleted
            += new EventHandler <WorkflowCompletedEventArgs>(
                   workflowRuntime_WorkflowCompleted);

        //get the input parameters
        Double dividendValue;
        Double divisorValue;

        Double.TryParse(dividend.Text, out dividendValue);
        Double.TryParse(divisor.Text, out divisorValue);

        //pass the input parameters to the workflow
        Dictionary <String, Object> wfArguments
            = new Dictionary <string, object>();

        wfArguments.Add("Dividend", dividendValue);
        wfArguments.Add("Divisor", divisorValue);

        //create and start the workflow
        WorkflowInstance instance = workflowRuntime.CreateWorkflow(
            typeof(SharedWorkflows.DivideNumbersWorkflow), wfArguments);

        instance.Start();

        //execute the workflow synchronously on our thread
        scheduler.RunWorkflow(instance.InstanceId);
    }
示例#24
0
        public WorkflowAsyncResult(string message, AsyncCallback callback, object state)
            : base(callback, state)
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("ReceivedData", message);

            //start the workflow
            WorkflowRuntime workflowRuntime          = new WorkflowRuntime();
            ManualWorkflowSchedulerService scheduler = new ManualWorkflowSchedulerService();

            workflowRuntime.AddService(scheduler);
            workflowRuntime.StartRuntime();

            workflowRuntime.WorkflowCompleted  += this.OnWorkflowCompleted;
            workflowRuntime.WorkflowTerminated += this.OnWorkflowTerminated;

            this.instance = workflowRuntime.CreateWorkflow(typeof(Workflow1), parameters);

            this.instance.Start();

            scheduler.RunWorkflow(this.instance.InstanceId);
        }
        protected object[] Invoke(Type interfaceType, string methodName, bool isActivation, object[] parameters)
        {
            EventHandler <WorkflowCompletedEventArgs> handler3 = null;

            object[]       objArray;
            Guid           workflowInstanceId = GetWorkflowInstanceId(ref isActivation);
            EventQueueName key              = new EventQueueName(interfaceType, methodName);
            MethodInfo     method           = interfaceType.GetMethod(methodName);
            bool           responseRequired = method.ReturnType != typeof(void);

            if (!responseRequired)
            {
                foreach (ParameterInfo info2 in method.GetParameters())
                {
                    if (info2.ParameterType.IsByRef || info2.IsOut)
                    {
                        responseRequired = true;
                        break;
                    }
                }
            }
            MethodMessage methodMessage = PrepareMessage(interfaceType, methodName, parameters, responseRequired);
            EventHandler <WorkflowTerminatedEventArgs> handler  = null;
            EventHandler <WorkflowCompletedEventArgs>  handler2 = null;

            try
            {
                WorkflowInstance workflow;
                if (isActivation)
                {
                    workflow = this.WorkflowRuntime.CreateWorkflow(this.workflowType, null, workflowInstanceId);
                    SafeEnqueueItem(workflow, key, methodMessage);
                    workflow.Start();
                }
                else
                {
                    workflow = this.WorkflowRuntime.GetWorkflow(workflowInstanceId);
                    SafeEnqueueItem(workflow, key, methodMessage);
                }
                bool workflowTerminated = false;
                handler = delegate(object sender, WorkflowTerminatedEventArgs e) {
                    if (e.WorkflowInstance.InstanceId.Equals(workflowInstanceId))
                    {
                        methodMessage.SendException(e.Exception);
                        workflowTerminated = true;
                    }
                };
                if (handler3 == null)
                {
                    handler3 = delegate(object sender, WorkflowCompletedEventArgs e) {
                        if (e.WorkflowInstance.InstanceId.Equals(workflowInstanceId))
                        {
                            methodMessage.SendException(new ApplicationException(SR.GetString(CultureInfo.CurrentCulture, "Error_WorkflowCompleted")));
                        }
                    };
                }
                handler2 = handler3;
                this.WorkflowRuntime.WorkflowTerminated += handler;
                this.WorkflowRuntime.WorkflowCompleted  += handler2;
                ManualWorkflowSchedulerService service = this.WorkflowRuntime.GetService <ManualWorkflowSchedulerService>();
                if (service != null)
                {
                    service.RunWorkflow(workflow.InstanceId);
                }
                if (!responseRequired)
                {
                    return(new object[0]);
                }
                IMethodResponseMessage message = methodMessage.WaitForResponseMessage();
                if (message.Exception != null)
                {
                    if (!workflowTerminated)
                    {
                        throw message.Exception;
                    }
                    throw new ApplicationException(SR.GetString(CultureInfo.CurrentCulture, "Error_WorkflowTerminated"), message.Exception);
                }
                if (message.OutArgs != null)
                {
                    return(((ArrayList)message.OutArgs).ToArray());
                }
                objArray = new object[0];
            }
            finally
            {
                if (handler != null)
                {
                    this.WorkflowRuntime.WorkflowTerminated -= handler;
                }
                if (handler2 != null)
                {
                    this.WorkflowRuntime.WorkflowCompleted -= handler2;
                }
            }
            return(objArray);
        }
示例#26
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage WorkflowThreading.exe [Single | Multi] [Delay | WaitForMessage]");
                return;
            }

            if (!args[0].Equals("Single", StringComparison.OrdinalIgnoreCase) && !args[0].Equals("Multi", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("Specify Single or Multi as a first command line parameter");
                return;
            }

            if (!args[1].Equals("Delay", StringComparison.OrdinalIgnoreCase) && !args[1].Equals("WaitForMessage", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("Specify Delay or WaitForMessage as a second command line parameter");
                return;
            }

            ThreadMonitor.Enlist(Thread.CurrentThread, "Host");
            Console.ForegroundColor = ConsoleColor.White;

            // Start the engine
            using (workflowRuntime = new WorkflowRuntime())
            {
                ManualWorkflowSchedulerService scheduler = null;
                if (args[0].ToString().Equals("Single", StringComparison.OrdinalIgnoreCase))
                {
                    scheduler = new ManualWorkflowSchedulerService();
                    workflowRuntime.AddService(scheduler);
                }

                workflowRuntime.StartRuntime();

                // Set up the workflow runtime event handlers
                workflowRuntime.WorkflowCompleted  += OnWorkflowCompleted;
                workflowRuntime.WorkflowTerminated += OnWorkflowTerminated;
                workflowRuntime.WorkflowIdled      += OnWorkflowIdled;
                workflowRuntime.WorkflowCreated    += OnWorkflowCreated;

                // Load the workflow type
                Type type = typeof(ThreadingWorkflow);
                Dictionary <string, object> workflowParameters = new Dictionary <string, object>();
                workflowParameters.Add("BranchFlag", args[1]);

                Console.WriteLine("\n--- Before Starting Workflow ---\n");

                // Create an instance of the workflow
                workflowInstance = workflowRuntime.CreateWorkflow(type, workflowParameters);
                workflowInstance.Start();

                Console.WriteLine("\n--- After Starting Workflow ---\n");

                if (scheduler != null)
                {
                    scheduler.RunWorkflow(workflowInstance.InstanceId);
                }
                readyHandle.WaitOne();

                if (args[1].Equals("WaitForMessage", StringComparison.OrdinalIgnoreCase))
                {
                    // Send message to WaitForMessageActivity's queue
                    workflowInstance.EnqueueItem("WaitForMessageActivityQueue", "Hello", null, null);
                }

                if (scheduler != null)
                {
                    scheduler.RunWorkflow(workflowInstance.InstanceId);
                }
                waitHandle.WaitOne();

                workflowRuntime.StopRuntime();
            }
        }
示例#27
0
        static private void RunWorkflowInScheduler(Guid instanceId)
        {
            ManualWorkflowSchedulerService scheduler = Runtime.GetService <ManualWorkflowSchedulerService>();

            scheduler.RunWorkflow(instanceId);
        }
示例#28
0
        protected Object[] Invoke(Type interfaceType, String methodName, bool isActivation, Object[] parameters)
        {
            Guid             workflowInstanceId = GetWorkflowInstanceId(ref isActivation);
            WorkflowInstance wfInstance;

            EventQueueName key = new EventQueueName(interfaceType, methodName);

            MethodInfo mInfo = interfaceType.GetMethod(methodName);

            bool responseRequired = (mInfo.ReturnType != typeof(void));

            if (!responseRequired)
            {
                foreach (ParameterInfo parameter in mInfo.GetParameters())
                {
                    if (parameter.ParameterType.IsByRef || parameter.IsOut)
                    {
                        responseRequired = true;
                        break;
                    }
                }
            }

            MethodMessage methodMessage = PrepareMessage(interfaceType, methodName, parameters, responseRequired);

            EventHandler <WorkflowTerminatedEventArgs> workflowTerminationHandler = null;
            EventHandler <WorkflowCompletedEventArgs>  workflowCompletedHandler   = null;

            try
            {
                if (isActivation)
                {
                    wfInstance = WorkflowRuntime.CreateWorkflow(this.workflowType, null, workflowInstanceId);
                    SafeEnqueueItem(wfInstance, key, methodMessage);
                    wfInstance.Start();
                }
                else
                {
                    wfInstance = WorkflowRuntime.GetWorkflow(workflowInstanceId);
                    SafeEnqueueItem(wfInstance, key, methodMessage);
                }

                bool workflowTerminated = false;

                //Handler for workflow termination in b/w outstanding req-response.
                workflowTerminationHandler = delegate(Object sender, WorkflowTerminatedEventArgs e)
                {
                    if (e.WorkflowInstance.InstanceId.Equals(workflowInstanceId))
                    {
                        methodMessage.SendException(e.Exception);
                        workflowTerminated = true;
                    }
                };

                workflowCompletedHandler = delegate(Object sender, WorkflowCompletedEventArgs e)
                {
                    if (e.WorkflowInstance.InstanceId.Equals(workflowInstanceId))
                    {
                        methodMessage.SendException(new ApplicationException(SR.GetString(System.Globalization.CultureInfo.CurrentCulture, SR.Error_WorkflowCompleted)));
                    }
                };

                WorkflowRuntime.WorkflowTerminated += workflowTerminationHandler;
                WorkflowRuntime.WorkflowCompleted  += workflowCompletedHandler;

                ManualWorkflowSchedulerService scheduler = WorkflowRuntime.GetService <ManualWorkflowSchedulerService>();

                if (scheduler != null)
                {
                    scheduler.RunWorkflow(wfInstance.InstanceId);
                }

                if (!responseRequired)
                {
                    // no ret, out or ref
                    return(new Object[] { });
                }

                IMethodResponseMessage response = methodMessage.WaitForResponseMessage();

                if (response.Exception != null)
                {
                    if (!workflowTerminated)
                    {
                        throw response.Exception;
                    }
                    else
                    {
                        throw new ApplicationException(SR.GetString(System.Globalization.CultureInfo.CurrentCulture, SR.Error_WorkflowTerminated), response.Exception);
                    }
                }

                if (response.OutArgs != null)
                {
                    return(((ArrayList)response.OutArgs).ToArray());
                }
                else
                {
                    return new Object[] { }
                };
            }
            finally
            {
                if (workflowTerminationHandler != null)
                {
                    WorkflowRuntime.WorkflowTerminated -= workflowTerminationHandler;
                }

                if (workflowCompletedHandler != null)
                {
                    WorkflowRuntime.WorkflowCompleted -= workflowCompletedHandler;
                }
            }
        }
        private WorkflowRuntime InitializeWorkflowRuntime()
        {
            WorkflowRuntime workflowRuntime;

            if (WorkflowRuntimeProviderPluginFacade.HasConfiguration)
            {
                string providerName = WorkflowRuntimeProviderRegistry.DefaultWorkflowRuntimeProviderName;

                workflowRuntime = WorkflowRuntimeProviderPluginFacade.GetWorkflowRuntime(providerName);
            }
            else
            {
                Log.LogVerbose(LogTitle, "Using default workflow runtime");
                workflowRuntime = new WorkflowRuntime();
            }


            _manualWorkflowSchedulerService = new ManualWorkflowSchedulerService(true);
            workflowRuntime.AddService(_manualWorkflowSchedulerService);

            _fileWorkflowPersistenceService = new FileWorkflowPersistenceService(SerializedWorkflowsDirectory);
            workflowRuntime.AddService(_fileWorkflowPersistenceService);

            _externalDataExchangeService = new ExternalDataExchangeService();
            workflowRuntime.AddService(_externalDataExchangeService);


            AddWorkflowLoggingEvents(workflowRuntime);


            workflowRuntime.WorkflowCompleted += (sender, args) =>
            {
                using (ThreadDataManager.EnsureInitialize())
                {
                    OnWorkflowInstanceTerminatedCleanup(args.WorkflowInstance.InstanceId);
                }
            };



            workflowRuntime.WorkflowAborted += (sender, args) =>
            {
                using (ThreadDataManager.EnsureInitialize())
                {
                    OnWorkflowInstanceTerminatedCleanup(args.WorkflowInstance.InstanceId);
                }
            };



            workflowRuntime.WorkflowTerminated += (sender, args) =>
            {
                using (ThreadDataManager.EnsureInitialize())
                {
                    OnWorkflowInstanceTerminatedCleanup(args.WorkflowInstance.InstanceId);
                }

                _resourceLocker.Resources.ExceptionFromWorkflow[Thread.CurrentThread.ManagedThreadId] = args.Exception;
            };



            workflowRuntime.WorkflowCreated += (sender, args) =>
                                               SetWorkflowInstanceStatus(args.WorkflowInstance.InstanceId, WorkflowInstanceStatus.Idle, true);

            workflowRuntime.WorkflowIdled += (sender, args) =>
                                             SetWorkflowInstanceStatus(args.WorkflowInstance.InstanceId, WorkflowInstanceStatus.Idle, false);

            workflowRuntime.WorkflowLoaded += (sender, args) =>
                                              SetWorkflowInstanceStatus(args.WorkflowInstance.InstanceId, WorkflowInstanceStatus.Idle, true);

            return(workflowRuntime);
        }
示例#30
0
        /// <summary>
        /// Get a reference to the manual workflow scheduler service.
        /// </summary>
        /// <returns></returns>
        private ManualWorkflowSchedulerService GetWorkflowSchedulerService()
        {
            ManualWorkflowSchedulerService scheduler = _WorkflowRuntime.GetService(typeof(ManualWorkflowSchedulerService)) as ManualWorkflowSchedulerService;

            return(scheduler);
        }