Esempio n. 1
0
        private void miCreateSequentialWorkflow_Click(object sender, EventArgs e)
        {
            // create a new sequential workflow
            WorkflowInstance workflowInstance = SampleWorkflowRuntime.Current.CreateSequentialWorkflow();

            if (_options.WorkflowSettings.ModifySequentialWorkflow)
            {
                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();

            SampleWorkflowRuntime.Current.RunWorkflow(workflowInstance.InstanceId);
        }
Esempio n. 2
0
        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);
        }
        private void LoadPersistedWorkflow(Guid instanceId)
        {
            WorkflowInstanceStatus status;

            if (!_resourceLocker.Resources.WorkflowStatusDictionary.TryGetValue(instanceId, out status) ||
                status != WorkflowInstanceStatus.Running)
            {
                // This will make the runtime load the persisted workflow
                WorkflowInstance workflowInstance = null;
                try
                {
                    workflowInstance = WorkflowRuntime.GetWorkflow(instanceId);
                }
                catch (InvalidOperationException)
                {
                    _fileWorkflowPersistenceService.RemovePersistedWorkflow(instanceId);
                }

                if (workflowInstance != null &&
                    !_resourceLocker.Resources.WorkflowPersistingTypeDictionary.ContainsKey(instanceId))
                {
                    Type workflowType = workflowInstance.GetWorkflowDefinition().GetType();
                    SetWorkflowPersistingType(workflowType, instanceId);
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Replace the entire rule definition for a workflow
        /// </summary>
        /// <param name="instance"></param>
        private static void ReplaceRuleDefinition(WorkflowInstance instance)
        {
            //create a workflow changes object
            WorkflowChanges wfChanges = new WorkflowChanges(
                instance.GetWorkflowDefinition());

            //get a stream from an externally saved .rules file
            Stream stream
                = new FileStream(@"ModifiedRule.rules",
                                 FileMode.Open, FileAccess.Read, FileShare.Read);

            //read the .rules file using an XmlReader
            using (XmlReader xmlReader = XmlReader.Create(
                       new StreamReader(stream)))
            {
                WorkflowMarkupSerializer markupSerializer
                    = new WorkflowMarkupSerializer();
                //deserialize the rule definitions
                RuleDefinitions ruleDefinitions
                    = markupSerializer.Deserialize(xmlReader)
                      as RuleDefinitions;
                if (ruleDefinitions != null)
                {
                    //replace the embedded rules definition
                    //with the new one that was deserialzed from a file
                    wfChanges.TransientWorkflow.SetValue(
                        RuleDefinitions.RuleDefinitionsProperty,
                        ruleDefinitions);

                    ValidateAndApplyChanges(instance, wfChanges);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Modify a single rule condition
        /// </summary>
        /// <param name="instance"></param>
        private static void ModifyRuleCondition(WorkflowInstance instance)
        {
            //create a workflow changes object
            WorkflowChanges wfChanges = new WorkflowChanges(
                instance.GetWorkflowDefinition());

            //retrieve the RuleDefinitions for the workflow
            RuleDefinitions ruleDefinitions
                = (RuleDefinitions)wfChanges.TransientWorkflow.GetValue(
                      RuleDefinitions.RuleDefinitionsProperty);

            if (ruleDefinitions != null)
            {
                if (ruleDefinitions.Conditions.Contains("conditionOne"))
                {
                    //retrieve the rule that we want to change
                    RuleExpressionCondition condition
                        = ruleDefinitions.Conditions["conditionOne"]
                          as RuleExpressionCondition;

                    //change the rule by setting the right side of the
                    //operation to 300 instead of the original value of 100.
                    //was:  this.TestNumber > 100
                    //now:  this.TestNumber > 300
                    CodeBinaryOperatorExpression codeExpression =
                        condition.Expression as CodeBinaryOperatorExpression;
                    codeExpression.Right = new CodePrimitiveExpression(300);

                    ValidateAndApplyChanges(instance, wfChanges);
                }
            }
        }
Esempio n. 6
0
        static void OnWorkflowIdle(object sender, WorkflowEventArgs e)
        {
            if (wasChanged)
            {
                return;
            }

            wasChanged = true;

            WorkflowInstance workflowInstance = e.WorkflowInstance;

            Int32 newAmount = 15000;

            Console.WriteLine("Dynamically change approved amount to {0:c}", newAmount);

            // Dynamic update of order rule
            WorkflowChanges workflowchanges = new WorkflowChanges(workflowInstance.GetWorkflowDefinition());

            CompositeActivity       transient       = workflowchanges.TransientWorkflow;
            RuleDefinitions         ruleDefinitions = (RuleDefinitions)transient.GetValue(RuleDefinitions.RuleDefinitionsProperty);
            RuleConditionCollection conditions      = ruleDefinitions.Conditions;
            RuleExpressionCondition condition1      = (RuleExpressionCondition)conditions["Check"];

            (condition1.Expression as CodeBinaryOperatorExpression).Right = new CodePrimitiveExpression(newAmount);

            workflowInstance.ApplyWorkflowChanges(workflowchanges);
        }
Esempio n. 7
0
        /// <summary>
        /// Add a new custom activity to the workflow instance
        /// </summary>
        /// <param name="instance"></param>
        private static void AddNewActivity(WorkflowInstance instance)
        {
            //create a workflow changes object
            WorkflowChanges wfChanges = new WorkflowChanges(
                instance.GetWorkflowDefinition());

            //find the SequenceActivity that is a placeholder
            //for new activities
            CompositeActivity placeholder
                = wfChanges.TransientWorkflow.GetActivityByName(
                      "sequencePlaceholder") as CompositeActivity;

            if (placeholder != null)
            {
                //create an instance of the new activity
                NewFunctionActivity newActivity
                    = new NewFunctionActivity();

                //bind the TestNumber property of the activity
                //to the TestNumber property of the workflow
#if UPDATES_RESTRICTED
                newActivity.SetBinding(
                    NewFunctionActivity.TestNumberProperty,
                    new ActivityBind("DynamicRestrictedWorkflow", "TestNumber"));
#else
                newActivity.SetBinding(
                    NewFunctionActivity.TestNumberProperty,
                    new ActivityBind("DynamicWorkflow", "TestNumber"));
#endif
                //add the new custom activity to the workflow
                placeholder.Activities.Add(newActivity);
                //apply the changes
                ValidateAndApplyChanges(instance, wfChanges);
            }
        }
        private void LogWorkflowChange(string change, WorkflowEventArgs args, bool logUserName, bool workflowDefinitionAvailable, bool error)
        {
            WorkflowInstance instance = null;

            string activityTypeName = null;

            try
            {
                instance = args.WorkflowInstance;
            }
            catch
            {
                // Silent
            }

            if (workflowDefinitionAvailable && instance != null)
            {
                try
                {
                    activityTypeName = instance.GetWorkflowDefinition().GetType().FullName;
                }
                catch
                {
                    // Silent
                }
            }

            var message = new StringBuilder("Workflow ").Append(change);

            if (activityTypeName != null)
            {
                message.Append(", Activity = " + activityTypeName);
            }

            if (instance != null)
            {
                message.Append(", Id = " + instance.InstanceId);
            }

            if (logUserName)
            {
                string identity = UserValidationFacade.IsLoggedIn() ? UserValidationFacade.GetUsername() : "(system process)";
                message.Append(", User = " + identity);
            }

            if (!error)
            {
                Log.LogVerbose(LogTitle, message.ToString());
            }
            else
            {
                Log.LogError(LogTitle, message.ToString());
            }
        }
Esempio n. 9
0
        private void AddOrderOnHoldState()
        {
            // Get a reference to the WorkflowInstance for the selected workflow
            WorkflowInstance instance =
                this.runtime.GetWorkflow(this.GetSelectedWorkflowInstanceID());

            // Get a reference to the root activity for the workflow
            Activity root = instance.GetWorkflowDefinition();

            // Create a new instance of the WorkflowChanges class for managing
            // the in-memory changes to the workflow
            WorkflowChanges changes = new WorkflowChanges(root);

            // Create a new State activity to the workflow
            StateActivity orderOnHoldState = new StateActivity();

            orderOnHoldState.Name = "OrderOnHoldState";

            // Add a new EventDriven activity to the State
            EventDrivenActivity eventDrivenDelay = new EventDrivenActivity();

            eventDrivenDelay.Name = "DelayOrderEvent";
            orderOnHoldState.Activities.Add(eventDrivenDelay);

            // Add a new Delay, initialized to 5 seconds
            DelayActivity delayOrder = new DelayActivity();

            delayOrder.Name            = "delayOrder";
            delayOrder.TimeoutDuration = new TimeSpan(0, 0, 5);
            eventDrivenDelay.Activities.Add(delayOrder);

            // Add a new SetState to the OrderOpenState
            SetStateActivity setStateOrderOpen = new SetStateActivity();

            setStateOrderOpen.TargetStateName = "OrderOpenState";
            eventDrivenDelay.Activities.Add(setStateOrderOpen);

            // Add the OnHoldState to the workflow
            changes.TransientWorkflow.Activities.Add(orderOnHoldState);

            // Apply the changes to the workflow instance
            try
            {
                instance.ApplyWorkflowChanges(changes);
            }
            catch (WorkflowValidationFailedException)
            {
                // New state has already been added
                MessageBox.Show("On Hold state has already been added to this workflow.");
            }
        }
Esempio n. 10
0
 private void SetWorkflowQueueInfo(Guid instanceId, Guid ParentWorkflowId)
 {
     if (instanceId != Guid.Empty && ParentWorkflowId != Guid.Empty)
     {
         if (!this._SubWorkflowService.IsContainChildWorkflow(instanceId, ParentWorkflowId))
         {
             WorkflowInstance parentInstance = this.GetWorkflowRuntime().GetWorkflow(ParentWorkflowId);
             WorkflowInstance childInstance  = this.GetWorkflowRuntime().GetWorkflow(instanceId);
             Activity         a = childInstance.GetWorkflowDefinition();
             a.GetType();
             ReadOnlyCollection <WorkflowQueueInfo> queue = parentInstance.GetWorkflowQueueData();
             this._SubWorkflowService.SetChildWorkflow(queue, instanceId, ParentWorkflowId, a.Name);
         }
     }
 }
Esempio n. 11
0
        static public WorkflowAction[] GetSubscribedActions(Guid workflowId)
        {
            List <WorkflowAction>       actions          = new List <WorkflowAction>();
            SqlTrackingQuery            sqlTrackingQuery = new SqlTrackingQuery(ConfigurationManager.ConnectionStrings[Constants.Database.TenantWorkflowStore].ConnectionString);
            SqlTrackingWorkflowInstance trackingWorkflow;

            if (!sqlTrackingQuery.TryGetWorkflow(workflowId, out trackingWorkflow) ||
                trackingWorkflow.Status == WorkflowStatus.Completed ||
                trackingWorkflow.Status == WorkflowStatus.Terminated)
            {
                return(actions.ToArray());
            }

            WorkflowInstance instance = Runtime.GetWorkflow(workflowId);
            Activity         workflow = instance.GetWorkflowDefinition();
            ReadOnlyCollection <WorkflowQueueInfo> queues = instance.GetWorkflowQueueData();

            foreach (WorkflowQueueInfo s in queues)
            {
                if (s.SubscribedActivityNames.Count == 0)
                {
                    continue;
                }
                EventQueueName eventQueueName = s.QueueName as EventQueueName;
                if (eventQueueName != null)
                {
                    WorkflowAction action = new WorkflowAction();
                    action.ActionName = eventQueueName.MethodName;
                    string   activityName  = s.SubscribedActivityNames[0];
                    string[] splittedNames = activityName.Split('.');
                    action.StepName = splittedNames[0];
                    HandleExternalEventActivity activity = workflow.GetActivityByName(activityName) as HandleExternalEventActivity;
                    if (activity != null && activity.Roles != null && activity.Roles.Count > 0)
                    {
                        List <string> roleNames = new List <string>();
                        foreach (WorkflowRole role in activity.Roles)
                        {
                            roleNames.Add(role.Name);
                        }
                        action.QualifiedRoles = roleNames.ToArray();
                    }
                    actions.Add(action);
                }
            }
            return(actions.ToArray());
        }
 public StateMachineWorkflowInstance(WorkflowRuntime runtime, Guid instanceId)
 {
     if (runtime == null)
     {
         throw new ArgumentNullException("runtime");
     }
     if (instanceId == Guid.Empty)
     {
         throw new ArgumentNullException("instanceId");
     }
     _runtime              = runtime;
     _instanceId           = instanceId;
     _workflowInstance     = runtime.GetWorkflow(instanceId);
     _stateMachineWorkflow = _workflowInstance.GetWorkflowDefinition() as StateMachineWorkflowActivity;
     if (_stateMachineWorkflow == null)
     {
         throw new ArgumentException(SR.GetStateMachineWorkflowRequired(), "instanceId");
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Delete an activity from the workflow instance
        /// </summary>
        /// <param name="instance"></param>
        private static void DeleteActivity(WorkflowInstance instance)
        {
            //create a workflow changes object
            WorkflowChanges wfChanges = new WorkflowChanges(
                instance.GetWorkflowDefinition());

            //find the activity we want to remove
            Activity activity =
                wfChanges.TransientWorkflow.GetActivityByName(
                    "codeFirstPart");

            if (activity != null)
            {
                //remove the activity from its parent
                activity.Parent.Activities.Remove(activity);
                //apply the changes
                ValidateAndApplyChanges(instance, wfChanges);
            }
        }
Esempio n. 14
0
        static void OnWorkflowIdled(object sender, WorkflowEventArgs e)
        {
            WorkflowInstance workflowInstance = e.WorkflowInstance;
            Activity         wRoot            = workflowInstance.GetWorkflowDefinition();

            //
            // use WorkflowChanges class to author dynamic change
            //
            WorkflowChanges changes = new WorkflowChanges(wRoot);

            Console.WriteLine("  Host is denying all PO requests - Removing POCreated step");
            //
            // remove POCreated activity
            //
            changes.TransientWorkflow.Activities.Remove(changes.TransientWorkflow.Activities["POCreated"]);
            //
            // apply transient changes to instance
            //
            workflowInstance.ApplyWorkflowChanges(changes);
        }
Esempio n. 15
0
        /// <summary>
        /// Tries the load from ms workflow.
        /// </summary>
        /// <returns></returns>
        private bool TryLoadFromMsWorkflow()
        {
            try
            {
                WorkflowInstance instance = GlobalWorkflowRuntime.WorkflowRuntime.GetWorkflow(this.InstanceId);
                Activity         root     = instance.GetWorkflowDefinition();

                if (this.WorkflowEntity == null)
                {
                    this.WorkflowEntity = BusinessManager.Load(WorkflowInstanceEntity.ClassName, new PrimaryKeyId(this.InstanceId));
                }

                this.InnerWorkflowChanges = new WorkflowChanges(root);
                this.TransientWorkflow    = this.InnerWorkflowChanges.TransientWorkflow;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.ToString(), "Mediachase.Ibn.Assignments::TryLoadFromMsWorkflow");
                return(false);
            }

            return(true);
        }
        public void UpgradeWorkflow(WorkflowRuntime runtime, Guid instanceId)
        {
            WorkflowInstance workflowInstance = runtime.GetWorkflow(instanceId);

            var definition = workflowInstance.GetWorkflowDefinition();

            if (!OldAssemblyNames.Contains(definition.GetType().Assembly.FullName))
            {
                return;
            }

            lock (GetLockForWorkflow(instanceId))
            {
                workflowInstance.Unload();

                var are = new AutoResetEvent(false);

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

                //Получаем перзистанс и извлекаем состояние
                var persistance = runtime.GetService <NotTerminatingSqlWorkflowPersistenceService>();

                persistance.OnArgsAllowed +=
                    delegate(object sender, NotTerminatingSqlWorkflowPersistenceService.WorkflowSavedParametersArgs e)
                {
                    if (e.InstanceId == instanceId)
                    {
                        parameters = e.Parameters;
                        are.Set();
                    }
                };

                workflowInstance = runtime.GetWorkflow(instanceId);

                definition = workflowInstance.GetWorkflowDefinition();
                if (!OldAssemblyNames.Contains(definition.GetType().Assembly.FullName))
                {
                    //Если версия изменилась то дальнейшие манипуляции не нужны
                    return;
                }

                are.WaitOne(10000);

                workflowInstance.Unload();

                using (var context = this.CreateContext())
                {
                    context.DeleteWorkflowInPesistenceStore(instanceId);
                    context.SubmitChanges();
                }
                var workflowState = WorkflowStateService.GetWorkflowState(instanceId);

                parameters.Add(StateMachineWithSimpleContainer.DontWriteToWorkflowHistoryPersistenceKey, true);

                using (var sync = new WorkflowSync(runtime, instanceId))
                {
                    if (!CreateWorkflowIfNotExists(runtime, instanceId, workflowState.Type, parameters))
                    //Это ожидание создания воркфлоу
                    {
                        sync.WaitHandle.WaitOne(600000);
                    }
                }

                var wfinstance = new StateMachineWorkflowInstance(runtime, instanceId);
                using (var sync = new WorkflowSync(runtime, instanceId))
                //Это ожидание завершения установки состояния воркфлоу
                {
                    wfinstance.SetState(workflowState.WorkflowStateName);
                    sync.WaitHandle.WaitOne(600000);
                }

                var args = new SetWorkflowInternalParametersEventArgs(instanceId,
                                                                      new Dictionary <string, object>()
                {
                    {
                        StateMachineWithSimpleContainer.
                        DontWriteToWorkflowHistoryPersistenceKey
                        ,
                        false
                    }
                });
                SetInternalParameters(null, args);
            }
        }