Exemplo n.º 1
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);
        }
Exemplo n.º 2
0
        public override object GetValue(object component)
        {
            if (component == null)
            {
                throw new ArgumentNullException("component");
            }
            RuleConditionReference reference = component as RuleConditionReference;

            if (reference == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.NotARuleConditionReference, new object[] { "component" }), "component");
            }
            if (reference.ConditionName != null)
            {
                RuleDefinitions ruleDefinitions = base.GetRuleDefinitions(component);
                if (ruleDefinitions != null)
                {
                    RuleConditionCollection conditions = ruleDefinitions.Conditions;
                    if ((conditions != null) && conditions.Contains(reference.ConditionName))
                    {
                        RuleExpressionCondition condition = (RuleExpressionCondition)conditions[reference.ConditionName];
                        return(condition.Expression);
                    }
                }
            }
            return(null);
        }
Exemplo n.º 3
0
        public override void SetValue(object component, object value)
        {
            if (component == null)
            {
                throw new ArgumentNullException("component");
            }
            RuleConditionReference reference = component as RuleConditionReference;

            if (reference == null)
            {
                throw new ArgumentNullException("component");
            }
            CodeExpression expression = value as CodeExpression;

            if (reference.ConditionName != null)
            {
                ISite serviceProvider = PropertyDescriptorUtils.GetSite(base.ServiceProvider, component);
                if (serviceProvider == null)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.MissingService, new object[] { typeof(ISite).FullName }));
                }
                RuleConditionCollection conditions  = null;
                RuleDefinitions         definitions = ConditionHelper.Load_Rules_DT(serviceProvider, Helpers.GetRootActivity(serviceProvider.Component as Activity));
                if (definitions != null)
                {
                    conditions = definitions.Conditions;
                }
                if ((conditions != null) && conditions.Contains(reference.ConditionName))
                {
                    RuleExpressionCondition condition = (RuleExpressionCondition)conditions[reference.ConditionName];
                    condition.Expression = expression;
                    ConditionHelper.Flush_Rules_DT(serviceProvider, Helpers.GetRootActivity(serviceProvider.Component as Activity));
                }
            }
        }
Exemplo 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);
                }
            }
        }
Exemplo 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);
                }
            }
        }
Exemplo n.º 6
0
        public override void SetValue(object component, object value)
        {
            if (component == null)
            {
                throw new ArgumentNullException("component");
            }
            RuleSetReference reference = component as RuleSetReference;

            if (reference == null)
            {
                throw new ArgumentNullException("component");
            }
            RuleSet item = value as RuleSet;

            if (!string.IsNullOrEmpty(reference.RuleSetName))
            {
                ISite serviceProvider = PropertyDescriptorUtils.GetSite(base.ServiceProvider, component);
                if (serviceProvider == null)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.MissingService, new object[] { typeof(ISite).FullName }));
                }
                RuleSetCollection ruleSets    = null;
                RuleDefinitions   definitions = ConditionHelper.Load_Rules_DT(serviceProvider, Helpers.GetRootActivity(serviceProvider.Component as Activity));
                if (definitions != null)
                {
                    ruleSets = definitions.RuleSets;
                }
                if ((ruleSets != null) && ruleSets.Contains(reference.RuleSetName))
                {
                    ruleSets.Remove(reference.RuleSetName);
                    ruleSets.Add(item);
                    ConditionHelper.Flush_Rules_DT(serviceProvider, Helpers.GetRootActivity(serviceProvider.Component as Activity));
                }
            }
        }
Exemplo n.º 7
0
        public override void PerformReflection(ReflectionContext context)
        {
            Type workflowType = ((WorkflowNode)context.CurrentTreeNode).WorkflowType;

            DependencyObject workflow = ((WorkflowNode)context.CurrentTreeNode).WorkflowType.InvokeMember(string.Empty, BindingFlags.CreateInstance, null, null, null, CultureInfo.InvariantCulture) as DependencyObject;

            if (workflow == null)
            {
                throw new ApplicationException("Could not create the workflow and cast to DependencyObject");
            }

            RuleDefinitions definitions = workflow.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions;

            if (definitions != null)
            {
                foreach (RuleCondition cond in definitions.Conditions)
                {
                    RuleNode node = new RuleNode();
                    node.Rule = cond;
                    node.SelectedImageIndex = node.ImageIndex = context.GetImageIndex(typeof(RuleComponent), RuleNodeImageName);

                    context.CurrentTreeNode.Nodes.Add(node);
                    ReflectChildComponents(context.CreateClone(node));
                }
            }
        }
        public override object GetValue(object component)
        {
            if (component == null)
            {
                throw new ArgumentNullException("component");
            }

            RuleSetReference ruleSetReference = component as RuleSetReference;

            if (!string.IsNullOrEmpty(ruleSetReference.RuleSetName))
            {
                RuleDefinitions rules = GetRuleDefinitions(component);
                if (rules != null)
                {
                    RuleSetCollection ruleSetCollection = rules.RuleSets;
                    if (ruleSetCollection != null && ruleSetCollection.Contains(ruleSetReference.RuleSetName))
                    {
                        //in this case, RuleExpressionCondition is the only type allowed in the ruleConditionCollection
                        RuleSet ruleSet = ruleSetCollection[ruleSetReference.RuleSetName];
                        return(ruleSet);
                    }
                }
            }
            return(null);
        }
        public override object GetValue(object component)
        {
            if (component == null)
            {
                throw new ArgumentNullException("component");
            }

            RuleConditionReference conditionDecl = component as RuleConditionReference;

            if (conditionDecl == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.NotARuleConditionReference, "component"), "component");
            }

            if (conditionDecl.ConditionName != null)
            {
                RuleDefinitions rules = GetRuleDefinitions(component);
                if (rules != null)
                {
                    RuleConditionCollection conditionDefs = rules.Conditions;
                    if (conditionDefs != null && conditionDefs.Contains(conditionDecl.ConditionName))
                    {
                        //in this case, RuleExpressionCondition is the only type allowed in the ruleConditionCollection
                        RuleExpressionCondition conditionDefinition = (RuleExpressionCondition)conditionDefs[conditionDecl.ConditionName];
                        return(conditionDefinition.Expression);
                    }
                }
            }
            return(null);
        }
Exemplo n.º 10
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            if (executionContext == null)
            {
                throw new ArgumentNullException("executionContext");
            }

            Activity declaringActivity = Helpers.GetDeclaringActivity(this);

            if (declaringActivity == null)
            {
                declaringActivity = Helpers.GetRootActivity(this);
            }

            RuleDefinitions ruleDefinitions = (RuleDefinitions)declaringActivity.GetValue(RuleDefinitions.RuleDefinitionsProperty);

            if (ruleDefinitions != null)
            {
                RuleSet ruleSet = ruleDefinitions.RuleSets[this.RuleSetReference.RuleSetName];
                if (ruleSet != null)
                {
                    ruleSet.Execute(declaringActivity, executionContext);
                }
            }
            return(ActivityExecutionStatus.Closed);
        }
Exemplo n.º 11
0
        public void GetRuleDefinitions()
        {
            var serializer = new WorkflowMarkupSerializer();

            _ruleDefinitions = new RuleDefinitions();

            Parallel.For(0, _rulesStream.Count, streamCounter =>
            {
                using (XmlReader reader = new XmlTextReader(_rulesStream[streamCounter]))
                {
                    var temp = serializer.Deserialize(reader) as RuleDefinitions;

                    if (temp == null)
                    {
                        return;
                    }

                    if (temp.RuleSets != null)
                    {
                        for (int i = 0; i < temp.RuleSets.Count; i++)
                        {
                            _ruleDefinitions.RuleSets.Add(temp.RuleSets[i]);
                        }
                    }
                    if (temp.Conditions != null)
                    {
                        for (int i = 0; i < temp.Conditions.Count; i++)
                        {
                            _ruleDefinitions.Conditions.Add(temp.Conditions[i]);
                        }
                    }
                }
            });
        }
Exemplo n.º 12
0
        public override object EditValue(ITypeDescriptorContext typeDescriptorContext, IServiceProvider serviceProvider, object o)
        {
            if (typeDescriptorContext == null)
            {
                throw new ArgumentNullException("typeDescriptorContext");
            }
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }
            object obj2 = o;
            RuleConditionReference instance = typeDescriptorContext.Instance as RuleConditionReference;

            if (((instance == null) || (instance.ConditionName == null)) || (instance.ConditionName.Length <= 0))
            {
                throw new ArgumentException(Messages.ConditionNameNotSet);
            }
            Activity          component = null;
            IReferenceService service   = serviceProvider.GetService(typeof(IReferenceService)) as IReferenceService;

            if (service != null)
            {
                component = service.GetComponent(typeDescriptorContext.Instance) as Activity;
            }
            RuleConditionCollection conditions  = null;
            RuleDefinitions         definitions = ConditionHelper.Load_Rules_DT(serviceProvider, Helpers.GetRootActivity(component));

            if (definitions != null)
            {
                conditions = definitions.Conditions;
            }
            if ((conditions != null) && !conditions.Contains(instance.ConditionName))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.ConditionNotFound, new object[] { instance.ConditionName }));
            }
            this.editorService = (IWindowsFormsEditorService)serviceProvider.GetService(typeof(IWindowsFormsEditorService));
            if (this.editorService != null)
            {
                CodeExpression expression = typeDescriptorContext.PropertyDescriptor.GetValue(typeDescriptorContext.Instance) as CodeExpression;
                try
                {
                    using (RuleConditionDialog dialog = new RuleConditionDialog(component, expression))
                    {
                        if (DialogResult.OK == this.editorService.ShowDialog(dialog))
                        {
                            obj2 = dialog.Expression;
                        }
                    }
                }
                catch (NotSupportedException)
                {
                    DesignerHelpers.DisplayError(Messages.Error_ExpressionNotSupported, Messages.ConditionEditor, serviceProvider);
                }
            }
            return(obj2);
        }
Exemplo n.º 13
0
        public ConditionBrowserDialog(Activity activity, string name) : base(activity, name)
        {
            RuleDefinitions definitions = ConditionHelper.Load_Rules_DT(activity.Site, Helpers.GetRootActivity(activity));

            if (definitions != null)
            {
                this.declarativeConditionCollection = definitions.Conditions;
            }
            base.InitializeListView(this.declarativeConditionCollection, name);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Deserialize the markup file
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private Activity DeserializeFromMarkup(String fileName)
        {
            Activity workflow = null;

            //construct a serialization manager.
            DesignerSerializationManager dsm
                = new DesignerSerializationManager();

            using (dsm.CreateSession())
            {
                using (XmlReader xmlReader
                           = XmlReader.Create(fileName))
                {
                    //deserialize the workflow from the XmlReader
                    WorkflowMarkupSerializer markupSerializer
                             = new WorkflowMarkupSerializer();
                    workflow = markupSerializer.Deserialize(
                        dsm, xmlReader) as Activity;

                    if (dsm.Errors.Count > 0)
                    {
                        WorkflowMarkupSerializationException error
                            = dsm.Errors[0]
                              as WorkflowMarkupSerializationException;
                        throw error;
                    }
                }

                //deserialize a .rules file is one exists
                String rulesFileName = GetRulesFileName(fileName);
                if (File.Exists(rulesFileName))
                {
                    //read the .rules file
                    using (XmlReader xmlReader
                               = XmlReader.Create(rulesFileName))
                    {
                        WorkflowMarkupSerializer markupSerializer
                            = new WorkflowMarkupSerializer();
                        //deserialize the rule definitions
                        RuleDefinitions ruleDefinitions
                            = markupSerializer.Deserialize(dsm, xmlReader)
                              as RuleDefinitions;
                        if (ruleDefinitions != null)
                        {
                            //add the rules definitions to the workflow
                            workflow.SetValue(
                                RuleDefinitions.RuleDefinitionsProperty,
                                ruleDefinitions);
                        }
                    }
                }
            }

            return(workflow);
        }
        public override object EditValue(ITypeDescriptorContext typeDescriptorContext, IServiceProvider serviceProvider, object o)
        {
            if (typeDescriptorContext == null)
            {
                throw new ArgumentNullException("typeDescriptorContext");
            }
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }
            object obj2 = o;
            WorkflowDesignerLoader loader = serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;

            if ((loader != null) && loader.InDebugMode)
            {
                throw new InvalidOperationException(Messages.DebugModeEditsDisallowed);
            }
            RuleSetReference instance = typeDescriptorContext.Instance as RuleSetReference;

            if (((instance == null) || (instance.RuleSetName == null)) || (instance.RuleSetName.Length <= 0))
            {
                throw new ArgumentException(Messages.RuleSetNameNotSet);
            }
            Activity          component = null;
            IReferenceService service   = serviceProvider.GetService(typeof(IReferenceService)) as IReferenceService;

            if (service != null)
            {
                component = service.GetComponent(typeDescriptorContext.Instance) as Activity;
            }
            RuleSetCollection ruleSets    = null;
            RuleDefinitions   definitions = ConditionHelper.Load_Rules_DT(serviceProvider, System.Workflow.Activities.Common.Helpers.GetRootActivity(component));

            if (definitions != null)
            {
                ruleSets = definitions.RuleSets;
            }
            if ((ruleSets != null) && !ruleSets.Contains(instance.RuleSetName))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.RuleSetNotFound, new object[] { instance.RuleSetName }));
            }
            this.editorService = (IWindowsFormsEditorService)serviceProvider.GetService(typeof(IWindowsFormsEditorService));
            if (this.editorService != null)
            {
                RuleSet ruleSet = ruleSets[instance.RuleSetName];
                using (RuleSetDialog dialog = new RuleSetDialog(component, ruleSet))
                {
                    if (DialogResult.OK == this.editorService.ShowDialog(dialog))
                    {
                        obj2 = dialog.RuleSet;
                    }
                }
            }
            return(obj2);
        }
        public override void SetValue(object component, object value)
        {
            if (component == null)
            {
                throw new ArgumentNullException("component");
            }

            RuleConditionReference conditionDecl = component as RuleConditionReference;

            if (conditionDecl == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.NotARuleConditionReference, "component"), "component");
            }

            string conditionName = value as string;

            if ((conditionName == null) || (conditionName.TrimEnd().Length == 0))
            {
                conditionName = string.Empty;
            }

            ISite site = PropertyDescriptorUtils.GetSite(this.ServiceProvider, component);

            if (site == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ISite).FullName);
                throw new InvalidOperationException(message);
            }

            RuleConditionCollection conditionDefinitions = null;
            RuleDefinitions         rules = ConditionHelper.Load_Rules_DT(site, Helpers.GetRootActivity(site.Component as Activity));

            if (rules != null)
            {
                conditionDefinitions = rules.Conditions;
            }

            if (conditionDefinitions != null && conditionName.Length != 0 && !conditionDefinitions.Contains(conditionName))
            {
                //in this case, RuleExpressionCondition is the only type allowed in the ruleConditionCollection
                RuleExpressionCondition newCondition = new RuleExpressionCondition();
                newCondition.Name = conditionName;
                conditionDefinitions.Add(newCondition);
                ConditionHelper.Flush_Rules_DT(site, Helpers.GetRootActivity(site.Component as Activity));
            }

            // Cause component change events to be fired.
            PropertyDescriptor propertyDescriptor = TypeDescriptor.GetProperties(component)["ConditionName"];

            if (propertyDescriptor != null)
            {
                PropertyDescriptorUtils.SetPropertyValue(site, propertyDescriptor, component, conditionName);
            }
        }
Exemplo n.º 17
0
        public void SaveRuleSet()
        {
            RuleDefinitions ruleDefinitions = new RuleDefinitions();

            ruleDefinitions.RuleSets.Add(createRuleSet);
            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
            XmlTextWriter            writer     = new XmlTextWriter("RackRateRules.rules", System.Text.Encoding.Unicode);

            serializer.Serialize(writer, ruleDefinitions);
            writer.Close();
        }
Exemplo n.º 18
0
 public TransformingMessageServiceBehavior(string ruleSet)
 {
     if (!string.IsNullOrWhiteSpace(ruleSet))
     {
         _ruleSetPath = ruleSet;
         WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
         XmlTextReader reader = new XmlTextReader(_ruleSetPath);
         RuleDefinitions rules = serializer.Deserialize(reader) 
             as RuleDefinitions;
         _ruleSet = rules.RuleSets[0];
     }
 }
Exemplo n.º 19
0
        public void CreateRuleSet()
        {
            createRuleSet = new RuleSet("CreateRackRate");

            // Define property and activity reference expressions through CodeDom functionality
            CodeThisReferenceExpression  thisRef     = new CodeThisReferenceExpression();
            CodeFieldReferenceExpression RoleNameRef = new CodeFieldReferenceExpression(thisRef, "RoleName");
            CodeFieldReferenceExpression ValidityRef = new CodeFieldReferenceExpression(thisRef, "Validity");
            CodeTypeReferenceExpression  RoleEnumRef = new CodeTypeReferenceExpression(typeof(RoleType));
            CodeFieldReferenceExpression OutputRef   = new CodeFieldReferenceExpression(thisRef, "Output");

            // IF RoleType != "SalesAdmin" AND ValidityLimit > 3
            // THEN Output = "invalid"
            Rule createRackRateRule = new Rule("CreatRackRateRule");

            createRuleSet.Rules.Add(createRackRateRule);

            // define first predicate: RoleType != "SalesAdmin"
            CodeBinaryOperatorExpression ruleRoleName = new CodeBinaryOperatorExpression();

            ruleRoleName.Left     = RoleNameRef;
            ruleRoleName.Operator = CodeBinaryOperatorType.IdentityInequality;
            ruleRoleName.Right    = new CodeFieldReferenceExpression(RoleEnumRef, "SalesAdmin");

            // define second predicate: Validity > 3
            CodeBinaryOperatorExpression ruleValidityTest = new CodeBinaryOperatorExpression();

            ruleValidityTest.Left     = ValidityRef;
            ruleValidityTest.Operator = CodeBinaryOperatorType.ValueEquality;
            ruleValidityTest.Right    = new CodePrimitiveExpression("3");

            // join the first two predicates into a single condition
            CodeBinaryOperatorExpression ruleCondition = new CodeBinaryOperatorExpression();

            ruleCondition.Left     = ruleRoleName;
            ruleCondition.Operator = CodeBinaryOperatorType.BooleanAnd;
            ruleCondition.Right    = ruleValidityTest;

            createRackRateRule.Condition = new RuleExpressionCondition(ruleCondition);

            // add the action: Output = invalid
            CodeAssignStatement ruleSurchargeAction = new CodeAssignStatement(OutputRef, new CodePrimitiveExpression("invalid"));

            createRackRateRule.ThenActions.Add(new RuleStatementAction(ruleSurchargeAction));

            // Add the ruleset
            RuleDefinitions ruleDef = new RuleDefinitions();

            ruleDef.RuleSets.Add(createRuleSet);

            // Set the RuleDefinitions on the workflow
            //this.SetValue(RuleDefinitions.RuleDefinitionsProperty, ruleDef);
        }
Exemplo n.º 20
0
        public RuleSetBrowserDialog(Activity activity, string name)
            : base(activity, name)
        {
            RuleDefinitions rules = ConditionHelper.Load_Rules_DT(activity.Site, Helpers.GetRootActivity(activity));

            if (rules != null)
            {
                this.ruleSetCollection = rules.RuleSets;
            }

            InitializeListView(this.ruleSetCollection, name);
        }
        protected override void DoDefaultAction()
        {
            base.DoDefaultAction();
            WorkflowDesignerLoader service = this.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;

            if ((service != null) && service.InDebugMode)
            {
                throw new InvalidOperationException(Messages.DebugModeEditsDisallowed);
            }
            PolicyActivity activity = (PolicyActivity)base.Activity;

            if (!System.Workflow.Activities.Common.Helpers.IsActivityLocked(activity))
            {
                RuleDefinitions definitions = ConditionHelper.Load_Rules_DT(this, System.Workflow.Activities.Common.Helpers.GetRootActivity(activity));
                if (definitions != null)
                {
                    RuleSetCollection ruleSets         = definitions.RuleSets;
                    RuleSetReference  ruleSetReference = activity.RuleSetReference;
                    RuleSet           ruleSet          = null;
                    string            key = null;
                    if ((ruleSetReference != null) && !string.IsNullOrEmpty(ruleSetReference.RuleSetName))
                    {
                        key = ruleSetReference.RuleSetName;
                        if (ruleSets.Contains(key))
                        {
                            ruleSet = ruleSets[key];
                        }
                    }
                    else
                    {
                        key = ruleSets.GenerateRuleSetName();
                    }
                    using (RuleSetDialog dialog = new RuleSetDialog(activity, ruleSet))
                    {
                        if (DialogResult.OK == dialog.ShowDialog())
                        {
                            if (ruleSet != null)
                            {
                                ruleSets.Remove(key);
                            }
                            else
                            {
                                dialog.RuleSet.Name       = key;
                                activity.RuleSetReference = new RuleSetReference(key);
                            }
                            ruleSets.Add(dialog.RuleSet);
                            ConditionHelper.Flush_Rules_DT(this, System.Workflow.Activities.Common.Helpers.GetRootActivity(activity));
                        }
                    }
                }
                TypeDescriptor.GetProperties(activity)["RuleSetReference"].SetValue(activity, activity.RuleSetReference);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// 克隆一个实例
        /// </summary>
        /// <param name="WfRuntimeClone"></param>
        /// <param name="instanceClone"></param>
        /// <param name="WfRuntime"></param>
        /// <returns></returns>
        public static WorkflowInstance CloneWorkflowInstance(WorkflowRuntime WfRuntimeClone, WorkflowInstance instanceClone, WorkflowRuntime WfRuntime)
        {
            try
            {
                if (!WfRuntimeClone.IsStarted)
                {
                    WfRuntimeClone.StartRuntime();
                }
                StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(WfRuntimeClone, instanceClone.InstanceId);

                System.Workflow.Activities.StateMachineWorkflowActivity smworkflow = new StateMachineWorkflowActivity();
                smworkflow = workflowinstance.StateMachineWorkflow;
                RuleDefinitions          ruleDefinitions  = smworkflow.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions;
                WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer();

                StringBuilder xoml       = new StringBuilder();
                StringBuilder rule       = new StringBuilder();
                XmlWriter     xmlWriter  = XmlWriter.Create(xoml);
                XmlWriter     ruleWriter = XmlWriter.Create(rule);
                markupSerializer.Serialize(xmlWriter, smworkflow);

                if (ruleDefinitions != null)
                {
                    markupSerializer.Serialize(ruleWriter, ruleDefinitions);
                }

                xmlWriter.Close();
                ruleWriter.Close();

                StringReader     readxoml   = new StringReader(xoml.ToString());
                XmlReader        readerxoml = XmlReader.Create(readxoml);
                WorkflowInstance instance;
                if (ruleDefinitions == null)
                {
                    instance = WfRuntime.CreateWorkflow(readerxoml);
                }
                else
                {
                    StringReader readrule   = new StringReader(rule.ToString());
                    XmlReader    readerrule = XmlReader.Create(readrule);
                    instance = WfRuntime.CreateWorkflow(readerxoml, readerrule, null);
                }

                instance.Start();
                return(instance);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("CloneWorkflowInstance异常信息 :" + ex.ToString());
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Execute a RuleSet definition read from
        /// a file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void codeExecuteRuleSet_ExecuteCode(
            object sender, EventArgs e)
        {
            //get a stream from the embedded .rules resource
            Assembly assembly = Assembly.GetAssembly(typeof(SellItemWorkflow));
            Stream   stream   = assembly.GetManifestResourceStream(
                "SharedWorkflows.SellItemMethods2Workflow.rules");

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

            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)
                {
                    if (ruleDefinitions.RuleSets.Contains("CalculateItemTotals"))
                    {
                        RuleSet rs
                            = ruleDefinitions.RuleSets["CalculateItemTotals"];
                        //validate and execute the RuleSet against this
                        //workflow instance
                        RuleValidation validation = new RuleValidation(
                            typeof(SellItemSerializedWorkflow), null);
                        if (rs.Validate(validation))
                        {
                            RuleExecution execution
                                = new RuleExecution(validation, this);
                            rs.Execute(execution);
                        }
                        else
                        {
                            foreach (ValidationError error in validation.Errors)
                            {
                                Console.WriteLine(error.ErrorText);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
        public RulesConverter(RulesExtractor ruleExtractor, bool runAsync)
        {
            if (ruleExtractor == null)
            {
                throw new ArgumentNullException("ruleExtractor");
            }

            if (ruleExtractor.RuleDefinitions == null)
            {
                SendMessage("Rule definitions have not been extracted", EventType.Output);
                ruleExtractor.GetRuleDefinitions();
            }

            _ruleDefinitions = ruleExtractor.RuleDefinitions;
            _runAsync        = runAsync;
        }
Exemplo n.º 25
0
        internal static string ConvertRuleConditionReference(RuleDefinitions ruleDefinitions, RuleConditionReference ruleRef)
        {
            var builder = new StringBuilder();

            builder.AppendFormat("This activity gets executed only if condition '{0}' is true", ruleRef.ConditionName);
            try
            {
                RuleCondition condition = ruleDefinitions.Conditions.First(x => x.Name != null && x.Name == ruleRef.ConditionName);
                builder.AppendFormat("[Condition Code: {0}]", ConvertRuleCondition(condition));
            }
            catch
            {
                // no condition, so don't append anything
            }

            return(builder.ToString());
        }
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object valueToConvert)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            string ruleSetName = valueToConvert as string;

            if ((ruleSetName == null) || (ruleSetName.TrimEnd().Length == 0))
            {
                ruleSetName = string.Empty;
            }

            ISite site = PropertyDescriptorUtils.GetSite(context, context.Instance);

            if (site == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ISite).FullName);
                throw new InvalidOperationException(message);
            }

            RuleSetCollection ruleSetCollection = null;
            RuleDefinitions   rules             = ConditionHelper.Load_Rules_DT(site, Helpers.GetRootActivity(site.Component as Activity));

            if (rules != null)
            {
                ruleSetCollection = rules.RuleSets;
            }

            if (ruleSetCollection != null && ruleSetName.Length != 0 && !ruleSetCollection.Contains(ruleSetName))
            {
                //in this case, RuleExpressionCondition is the only type allowed in the ruleConditionCollection
                RuleSet newRuleSet = new RuleSet();
                newRuleSet.Name = ruleSetName;
                ruleSetCollection.Add(newRuleSet);
                ConditionHelper.Flush_Rules_DT(site, Helpers.GetRootActivity(site.Component as Activity));
            }

            RuleSetReference ruleSetReference = new RuleSetReference();

            ruleSetReference.RuleSetName = ruleSetName;

            return(ruleSetReference);
        }
Exemplo n.º 27
0
        protected override void Execute(CodeActivityContext context)
        {
            if (RulesFilePath == null || RuleSetName == null)
            {
                throw new InvalidOperationException("Rules File path and RuleSet Name need to be configured");
            }

            if (!File.Exists(RulesFilePath))
            {
                throw new InvalidOperationException("Rules File " + RulesFilePath + " did not exist");
            }

            // Get the RuleSet from the .rules file
            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
            XmlTextReader            reader     = new XmlTextReader(RulesFilePath);
            RuleDefinitions          rules      = serializer.Deserialize(reader) as RuleDefinitions;
            RuleSet ruleSet = rules.RuleSets[RuleSetName];

            if (ruleSet == null)
            {
                throw new InvalidOperationException("RuleSet " + RuleSetName + " not found in " + RulesFilePath);
            }

            // Validate before running
            Type           targetType = this.TargetObject.Get(context).GetType();
            RuleValidation validation = new RuleValidation(targetType, null);

            if (!ruleSet.Validate(validation))
            {
                // Set the ValidationErrors OutArgument
                this.ValidationErrors.Set(context, validation.Errors);

                // Throw exception
                throw new ValidationException(string.Format("The ruleset is not valid. {0} validation errors found (check the ValidationErrors property for more information).", validation.Errors.Count));
            }

            // Execute the ruleset
            object     evaluatedTarget = this.TargetObject.Get(context);
            RuleEngine engine          = new RuleEngine(ruleSet, validation);

            engine.Execute(evaluatedTarget);

            // Update the Result object
            this.ResultObject.Set(context, evaluatedTarget);
        }
Exemplo n.º 28
0
        public override void SetValue(object component, object value)
        {
            if (component == null)
            {
                throw new ArgumentNullException("component");
            }
            if (!(component is RuleConditionReference))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.NotARuleConditionReference, new object[] { "component" }), "component");
            }
            string key = value as string;

            if ((key == null) || (key.TrimEnd(new char[0]).Length == 0))
            {
                key = string.Empty;
            }
            ISite serviceProvider = PropertyDescriptorUtils.GetSite(base.ServiceProvider, component);

            if (serviceProvider == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.MissingService, new object[] { typeof(ISite).FullName }));
            }
            RuleConditionCollection conditions  = null;
            RuleDefinitions         definitions = ConditionHelper.Load_Rules_DT(serviceProvider, Helpers.GetRootActivity(serviceProvider.Component as Activity));

            if (definitions != null)
            {
                conditions = definitions.Conditions;
            }
            if (((conditions != null) && (key.Length != 0)) && !conditions.Contains(key))
            {
                RuleExpressionCondition item = new RuleExpressionCondition {
                    Name = key
                };
                conditions.Add(item);
                ConditionHelper.Flush_Rules_DT(serviceProvider, Helpers.GetRootActivity(serviceProvider.Component as Activity));
            }
            PropertyDescriptor propertyDescriptor = TypeDescriptor.GetProperties(component)["ConditionName"];

            if (propertyDescriptor != null)
            {
                PropertyDescriptorUtils.SetPropertyValue(serviceProvider, propertyDescriptor, component, key);
            }
        }
        public override void SetValue(object component, object value)
        {
            if (component == null)
            {
                throw new ArgumentNullException("component");
            }

            RuleConditionReference conditionDecl = component as RuleConditionReference;

            if (conditionDecl == null)
            {
                throw new ArgumentNullException("component");
            }

            CodeExpression expression = value as CodeExpression;

            if (conditionDecl.ConditionName != null)
            {
                ISite site = PropertyDescriptorUtils.GetSite(this.ServiceProvider, component);
                if (site == null)
                {
                    string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ISite).FullName);
                    throw new InvalidOperationException(message);
                }

                RuleConditionCollection conditionDefs = null;
                RuleDefinitions         rules         = ConditionHelper.Load_Rules_DT(site, Helpers.GetRootActivity(site.Component as Activity));
                if (rules != null)
                {
                    conditionDefs = rules.Conditions;
                }

                if (conditionDefs != null && conditionDefs.Contains(conditionDecl.ConditionName))
                {
                    //in this case, RuleExpressionCondition is the only type allowed in the ruleConditionCollection
                    RuleExpressionCondition conditionDefinition = (RuleExpressionCondition)conditionDefs[conditionDecl.ConditionName];
                    conditionDefinition.Expression = expression;
                    ConditionHelper.Flush_Rules_DT(site, Helpers.GetRootActivity(site.Component as Activity));
                }
            }
        }
Exemplo n.º 30
0
        private ValidationErrorCollection ApplyRuleSet(T target,
                                                       String path, String setName)
        {
            ValidationErrorCollection errors = null;

            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();

            RuleSet rs = null;

            if (File.Exists(path))
            {
                using (XmlTextReader reader = new XmlTextReader(path))
                {
                    RuleDefinitions rules =
                        serializer.Deserialize(reader) as RuleDefinitions;
                    if (rules != null && rules.RuleSets.Contains(setName))
                    {
                        rs = rules.RuleSets[setName];
                    }
                }
            }

            if (rs == null)
            {
                throw new ArgumentException(String.Format(
                                                "Unable to retrieve RuleSet {0} from {1}", setName, path));
            }

            RuleValidation val = new RuleValidation(target.GetType(), null);

            if (!rs.Validate(val))
            {
                errors = val.Errors;
                return(errors);
            }

            RuleEngine rulesEngine = new RuleEngine(rs, val);

            rulesEngine.Execute(target);
            return(errors);
        }