Exemplo n.º 1
0
        public MSRuleSetExecutionResult ExecuteRuleSet(System.Workflow.Activities.Rules.RuleSet ruleSet, bool translatedRule)
        {
            MSRuleSetExecutionResult ruleSetExecutionResult = null;

            if (translatedRule)
            {
                ruleSetExecutionResult = new MSRuleSetExecutionResult(_msRuleSetTranslationResult);
            }
            else
            {
                ruleSetExecutionResult = new MSRuleSetExecutionResult();
            }

            RuleValidation rv = new RuleValidation(typeof(T), null);

            ruleSet.Validate(rv);

            ValidationErrorCollection errors = rv.Errors;

            if (errors.Count > 0)
            {
                ruleSetExecutionResult.AddRuleSetValidationErrors(errors);
            }
            else
            {
                try
                {
                    ExecuteRuleSet(ruleSet, rv, ref ruleSetExecutionResult);
                }
                catch (RuleException rex)
                {
                    _log.Error("RuleSet Name:  " + ruleSet.Name + "threw a Rule Exception during its execution.  ", rex);
                    ruleSetExecutionResult.AddExecutionError(Guid.Empty.ToString(), ruleSet.Name, rex);
                }
                catch (TargetInvocationException tex)
                {
                    _log.Error("RuleSetName:  " + ruleSet.Name +
                               ", threw a Target Invocation Exception which means that the Wrapper object itself probably threw an error, maybe the rule is targeting a property that is null or not a valid value for comparison", tex);
                    ruleSetExecutionResult.AddExecutionError(Guid.Empty.ToString(), ruleSet.Name, tex);
                }
                catch (Exception ex)
                {
                    _log.Error("RuleSetName:  " + ruleSet.Name + "Unhandled exception during execution of", ex);
                    ruleSetExecutionResult.AddExecutionError(Guid.Empty.ToString(), ruleSet.Name, ex);
                }
            }

            return(ruleSetExecutionResult);
        }
 internal RuleEngine(RuleSet ruleSet, RuleValidation validation, ActivityExecutionContext executionContext)
 {
     if (!ruleSet.Validate(validation))
     {
         throw new RuleSetValidationException(string.Format(CultureInfo.CurrentCulture, Messages.RuleSetValidationFailed, new object[] { ruleSet.name }), validation.Errors);
     }
     this.name = ruleSet.Name;
     this.validation = validation;
     Tracer tracer = null;
     if (WorkflowActivityTrace.Rules.Switch.ShouldTrace(TraceEventType.Information))
     {
         tracer = new Tracer(ruleSet.Name, executionContext);
     }
     this.analyzedRules = Executor.Preprocess(ruleSet.ChainingBehavior, ruleSet.Rules, validation, tracer);
 }
        internal RuleEngine(RuleSet ruleSet, RuleValidation validation, ActivityExecutionContext executionContext)
        {
            if (!ruleSet.Validate(validation))
            {
                throw new RuleSetValidationException(string.Format(CultureInfo.CurrentCulture, Messages.RuleSetValidationFailed, new object[] { ruleSet.name }), validation.Errors);
            }
            this.name       = ruleSet.Name;
            this.validation = validation;
            Tracer tracer = null;

            if (WorkflowActivityTrace.Rules.Switch.ShouldTrace(TraceEventType.Information))
            {
                tracer = new Tracer(ruleSet.Name, executionContext);
            }
            this.analyzedRules = Executor.Preprocess(ruleSet.ChainingBehavior, ruleSet.Rules, validation, tracer);
        }
        public RuleEngine(RuleSet ruleSet, RuleValidation validation)
        {
            // now validate it
            if (!ruleSet.Validate(validation))
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.RuleSetValidationFailed, ruleSet.name);
                throw new RuleSetValidationException(message, validation.Errors);
            }

            this.name       = ruleSet.Name;
            this.validation = validation;
            Tracer tracer = null;

            if (WorkflowActivityTrace.Rules.Switch.ShouldTrace(TraceEventType.Information))
            {
                tracer = new Tracer(ruleSet.Name);
            }
            this.analyzedRules = Executor.Preprocess(ruleSet.ChainingBehavior, ruleSet.Rules, validation, tracer);
        }
Exemplo n.º 5
0
        internal static bool ValidateRuleSet(System.Workflow.Activities.Rules.RuleSet ruleSetToValidate, Type targetType, bool promptForContinue)
        {
            if (ruleSetToValidate == null)
            {
                MessageBox.Show("No RuleSet selected.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if (targetType == null)
            {
                MessageBox.Show("No Type is associated with the RuleSet.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            var ruleValidation = new RuleValidation(targetType, null);

            ruleSetToValidate.Validate(ruleValidation);
            if (ruleValidation.Errors.Count == 0)
            {
                return(true);
            }
            var validationDialog = new ValidationErrorsForm();

            validationDialog.SetValidationErrors(ruleValidation.Errors);
            validationDialog.PromptForContinue = promptForContinue;
            validationDialog.ErrorText         = "The RuleSet failed validation.  Ensure that the selected Type has the public members referenced by this RuleSet.  Note that false errors may occur if you are referencing different copies of an assembly with the same strong name.";
            if (promptForContinue)
            {
                validationDialog.ErrorText += "  Select Continue to proceed or Cancel to return.";
            }

            validationDialog.ShowDialog();

            if (!promptForContinue)
            {
                return(false);
            }
            return(validationDialog.ContinueWithChange);
        }
Exemplo n.º 6
0
        internal static bool ValidateRuleSet(RuleSet ruleSetToValidate, Type targetType, bool promptForContinue)
        {
            if (ruleSetToValidate == null)
            {
                MessageBox.Show("No RuleSet selected.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;  
            }

            if (targetType == null)
            {
                MessageBox.Show("No Type is associated with the RuleSet.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;  
            }

            RuleValidation ruleValidation = new RuleValidation(targetType, null);
            ruleSetToValidate.Validate(ruleValidation);
            if (ruleValidation.Errors.Count == 0)
            {
                return true;
            }
            else
            {
                ValidationErrorsForm validationDialog = new ValidationErrorsForm();
                validationDialog.SetValidationErrors(ruleValidation.Errors);
                validationDialog.PromptForContinue = promptForContinue;
                validationDialog.ErrorText = "The RuleSet failed validation.  Ensure that the selected Type has the public members referenced by this RuleSet.  Note that false errors may occur if you are referencing different copies of an assembly with the same strong name.";
                if (promptForContinue)
                    validationDialog.ErrorText += "  Select Continue to proceed or Cancel to return.";
                
                validationDialog.ShowDialog();

                if (!promptForContinue)
                    return false;
                else
                    return validationDialog.ContinueWithChange;
            }
        }
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            RuleSetReference ruleSetReference = obj as RuleSetReference;

            if (ruleSetReference == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.UnexpectedArgumentType, typeof(RuleSetReference).FullName, "obj");
                throw new ArgumentException(message, "obj");
            }
            Activity activity = manager.Context[typeof(Activity)] as Activity;

            if (activity == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, typeof(Activity).Name);
                throw new InvalidOperationException(message);
            }
            PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext;

            if (validationContext == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, typeof(PropertyValidationContext).Name);
                throw new InvalidOperationException(message);
            }
            if (!string.IsNullOrEmpty(ruleSetReference.RuleSetName))
            {
                RuleDefinitions   rules             = null;
                RuleSetCollection ruleSetCollection = null;

                CompositeActivity declaringActivity = Helpers.GetDeclaringActivity(activity);
                if (declaringActivity == null)
                {
                    declaringActivity = Helpers.GetRootActivity(activity) as CompositeActivity;
                }
                if (activity.Site != null)
                {
                    rules = ConditionHelper.Load_Rules_DT(activity.Site, declaringActivity);
                }
                else
                {
                    rules = ConditionHelper.Load_Rules_RT(declaringActivity);
                }

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

                if (ruleSetCollection == null || !ruleSetCollection.Contains(ruleSetReference.RuleSetName))
                {
                    string          message         = string.Format(CultureInfo.CurrentCulture, Messages.RuleSetNotFound, ruleSetReference.RuleSetName);
                    ValidationError validationError = new ValidationError(message, ErrorNumbers.Error_RuleSetNotFound);
                    validationError.PropertyName = GetFullPropertyName(manager) + "." + "RuleSetName";
                    validationErrors.Add(validationError);
                }
                else
                {
                    RuleSet actualRuleSet = ruleSetCollection[ruleSetReference.RuleSetName];

                    ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider));

                    IDisposable localContextScope = (WorkflowCompilationContext.Current == null ? WorkflowCompilationContext.CreateScope(manager) : null);
                    try
                    {
                        RuleValidation validation = new RuleValidation(activity, typeProvider, WorkflowCompilationContext.Current.CheckTypes);
                        actualRuleSet.Validate(validation);
                        ValidationErrorCollection actualRuleSetErrors = validation.Errors;

                        if (actualRuleSetErrors.Count > 0)
                        {
                            string expressionPropertyName = GetFullPropertyName(manager);
                            string genericErrorMsg        = string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleSetExpression, expressionPropertyName);
                            int    errorNumber            = ErrorNumbers.Error_InvalidRuleSetExpression;

                            if (activity.Site != null)
                            {
                                foreach (ValidationError actualError in actualRuleSetErrors)
                                {
                                    ValidationError validationError = new ValidationError(actualError.ErrorText, errorNumber);
                                    validationError.PropertyName = expressionPropertyName + "." + "RuleSet Definition";
                                    validationErrors.Add(validationError);
                                }
                            }
                            else
                            {
                                foreach (ValidationError actualError in actualRuleSetErrors)
                                {
                                    ValidationError validationError = new ValidationError(genericErrorMsg + " " + actualError.ErrorText, errorNumber);
                                    validationError.PropertyName = expressionPropertyName;
                                    validationErrors.Add(validationError);
                                }
                            }
                        }
                        //
                    }
                    finally
                    {
                        if (localContextScope != null)
                        {
                            localContextScope.Dispose();
                        }
                    }
                }
            }
            else
            {
                string          message         = string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleSetName, "RuleSetReference");
                ValidationError validationError = new ValidationError(message, ErrorNumbers.Error_InvalidRuleSetName);
                validationError.PropertyName = GetFullPropertyName(manager) + "." + "RuleSetName";
                validationErrors.Add(validationError);
            }
            return(validationErrors);
        }
Exemplo n.º 8
0
		public static RuleSet BuildRuleSet(DataTable dtRules, RuleValidation validation)
		{
			RuleSet        rules = new RuleSet("RuleSet 1");
			RulesParser    parser = new RulesParser(validation);

			DataView vwRules = new DataView(dtRules);
			vwRules.RowFilter = "ACTIVE = 1";
			vwRules.Sort      = "PRIORITY asc";
			foreach ( DataRowView row in vwRules )
			{
				string sRULE_NAME    = Sql.ToString (row["RULE_NAME"   ]);
				int    nPRIORITY     = Sql.ToInteger(row["PRIORITY"    ]);
				string sREEVALUATION = Sql.ToString (row["REEVALUATION"]);
				bool   bACTIVE       = Sql.ToBoolean(row["ACTIVE"      ]);
				string sCONDITION    = Sql.ToString (row["CONDITION"   ]);
				string sTHEN_ACTIONS = Sql.ToString (row["THEN_ACTIONS"]);
				string sELSE_ACTIONS = Sql.ToString (row["ELSE_ACTIONS"]);
				
				RuleExpressionCondition condition      = parser.ParseCondition    (sCONDITION   );
				List<RuleAction>        lstThenActions = parser.ParseStatementList(sTHEN_ACTIONS);
				List<RuleAction>        lstElseActions = parser.ParseStatementList(sELSE_ACTIONS);
				System.Workflow.Activities.Rules.Rule r = new System.Workflow.Activities.Rules.Rule(sRULE_NAME, condition, lstThenActions, lstElseActions);
				r.Priority = nPRIORITY;
				r.Active   = bACTIVE  ;
				//r.ReevaluationBehavior = (RuleReevaluationBehavior) Enum.Parse(typeof(RuleReevaluationBehavior), sREEVALUATION);
				// 12/04/2010   Play it safe and never-reevaluate. 
				r.ReevaluationBehavior = RuleReevaluationBehavior.Never;
				rules.Rules.Add(r);
			}
			rules.Validate(validation);
			if ( validation.Errors.HasErrors )
			{
				throw(new Exception(RulesUtil.GetValidationErrors(validation)));
			}
			return rules;
		}
Exemplo n.º 9
0
		// 12/12/2012   For security reasons, we want to restrict the data types available to the rules wizard. 
		public static void RulesValidate(Guid gID, string sRULE_NAME, int nPRIORITY, string sREEVALUATION, bool bACTIVE, string sCONDITION, string sTHEN_ACTIONS, string sELSE_ACTIONS, Type thisType, SplendidRulesTypeProvider typeProvider)
		{
			RuleSet        rules      = new RuleSet("RuleSet 1");
			RuleValidation validation = new RuleValidation(thisType, typeProvider);
			RulesParser    parser     = new RulesParser(validation);
			RuleExpressionCondition condition      = parser.ParseCondition    (sCONDITION   );
			List<RuleAction>        lstThenActions = parser.ParseStatementList(sTHEN_ACTIONS);
			List<RuleAction>        lstElseActions = parser.ParseStatementList(sELSE_ACTIONS);

			System.Workflow.Activities.Rules.Rule r = new System.Workflow.Activities.Rules.Rule(sRULE_NAME, condition, lstThenActions, lstElseActions);
			r.Priority = nPRIORITY;
			r.Active   = bACTIVE  ;
			//r.ReevaluationBehavior = (RuleReevaluationBehavior) Enum.Parse(typeof(RuleReevaluationBehavior), sREEVALUATION);
			// 12/04/2010   Play it safe and never-reevaluate. 
			r.ReevaluationBehavior = RuleReevaluationBehavior.Never;
			rules.Rules.Add(r);
			rules.Validate(validation);
			if ( validation.Errors.HasErrors )
			{
				throw(new Exception(GetValidationErrors(validation)));
			}
		}
Exemplo n.º 10
0
        public MSRuleSetEvaluationResult EvaluateRuleSet(System.Workflow.Activities.Rules.RuleSet ruleSet, bool translatedRule)
        {
            MSRuleSetEvaluationResult ruleSetEvaluationResult = null;

            if (translatedRule)
            {
                ruleSetEvaluationResult = new MSRuleSetEvaluationResult(_msRuleSetTranslationResult);
            }
            else
            {
                ruleSetEvaluationResult = new MSRuleSetEvaluationResult();
            }

            RuleValidation rv = new RuleValidation(typeof(T), null);

            ruleSet.Validate(rv);

            ValidationErrorCollection errors = rv.Errors;

            if (errors.Count > 0)
            {
                //string validationErrorMessages = Helper.GetErrorMessageFromValidationErrorsCollection(errors);

                // if the rule set has errors at top level should we stop here or try each individual rule?  i think for now
                //we can continue to try each individual rule and then after evaluations report the errors in the return execution result
                //object

                ruleSetEvaluationResult.AddRuleSetValidationErrors(errors);
            }

            foreach (System.Workflow.Activities.Rules.Rule rule in ruleSet.Rules)
            {
                if (rule.Active)
                {
                    try
                    {
                        EvaluateRule(rule, ref ruleSetEvaluationResult, ref rv);
                    }
                    catch (RuleEvaluationException rex)
                    {
                        //_log.Error("Rule Name:  " + rule.Name + "threw a Rule Evaluation Exception during its evaluation.  ", rex);
                        //loop again cause if this one failed we still want to try to evaluate the other rules in this rule set
                        if (rex.InnerException != null)
                        {
                            ruleSetEvaluationResult.AddEvaluationError(rule.Name, rule.Description, (Exception)rex.InnerException);
                        }
                        else
                        {
                            ruleSetEvaluationResult.AddEvaluationError(rule.Name, rule.Description, (Exception)rex);
                        }
                        continue;
                    }
                    catch (Exception ex)
                    {
                        //_log.Error("Unhandled exception during evaluation of Rule Name:  " + rule.Name, ex);
                        ruleSetEvaluationResult.AddEvaluationError(rule.Name, rule.Description, ex);
                        continue;
                    }
                }
                else
                {
                    ruleSetEvaluationResult.AddRuleToInactive(rule.Name, rule.Description);
                }
            }

            return(ruleSetEvaluationResult);
        }
Exemplo n.º 11
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection errors    = base.Validate(manager, obj);
            RuleSetReference          reference = obj as RuleSetReference;

            if (reference == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.UnexpectedArgumentType, new object[] { typeof(RuleSetReference).FullName, "obj" }), "obj");
            }
            Activity activity = manager.Context[typeof(Activity)] as Activity;

            if (activity == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, new object[] { typeof(Activity).Name }));
            }
            if (!(manager.Context[typeof(PropertyValidationContext)] is PropertyValidationContext))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, new object[] { typeof(PropertyValidationContext).Name }));
            }
            if (!string.IsNullOrEmpty(reference.RuleSetName))
            {
                RuleDefinitions   definitions       = null;
                RuleSetCollection ruleSets          = null;
                CompositeActivity declaringActivity = Helpers.GetDeclaringActivity(activity);
                if (declaringActivity == null)
                {
                    declaringActivity = Helpers.GetRootActivity(activity) as CompositeActivity;
                }
                if (activity.Site != null)
                {
                    definitions = ConditionHelper.Load_Rules_DT(activity.Site, declaringActivity);
                }
                else
                {
                    definitions = ConditionHelper.Load_Rules_RT(declaringActivity);
                }
                if (definitions != null)
                {
                    ruleSets = definitions.RuleSets;
                }
                if ((ruleSets == null) || !ruleSets.Contains(reference.RuleSetName))
                {
                    ValidationError error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.RuleSetNotFound, new object[] { reference.RuleSetName }), 0x576)
                    {
                        PropertyName = base.GetFullPropertyName(manager) + ".RuleSetName"
                    };
                    errors.Add(error);
                    return(errors);
                }
                RuleSet       set     = ruleSets[reference.RuleSetName];
                ITypeProvider service = (ITypeProvider)manager.GetService(typeof(ITypeProvider));
                using ((WorkflowCompilationContext.Current == null) ? WorkflowCompilationContext.CreateScope(manager) : null)
                {
                    RuleValidation validation = new RuleValidation(activity, service, WorkflowCompilationContext.Current.CheckTypes);
                    set.Validate(validation);
                    ValidationErrorCollection errors2 = validation.Errors;
                    if (errors2.Count > 0)
                    {
                        string fullPropertyName = base.GetFullPropertyName(manager);
                        string str6             = string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleSetExpression, new object[] { fullPropertyName });
                        int    errorNumber      = 0x577;
                        if (activity.Site != null)
                        {
                            foreach (ValidationError error2 in errors2)
                            {
                                ValidationError error3 = new ValidationError(error2.ErrorText, errorNumber)
                                {
                                    PropertyName = fullPropertyName + ".RuleSet Definition"
                                };
                                errors.Add(error3);
                            }
                            return(errors);
                        }
                        foreach (ValidationError error4 in errors2)
                        {
                            ValidationError error5 = new ValidationError(str6 + " " + error4.ErrorText, errorNumber)
                            {
                                PropertyName = fullPropertyName
                            };
                            errors.Add(error5);
                        }
                    }
                    return(errors);
                }
            }
            ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleSetName, new object[] { "RuleSetReference" }), 0x578)
            {
                PropertyName = base.GetFullPropertyName(manager) + ".RuleSetName"
            };

            errors.Add(item);
            return(errors);
        }