internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
 {
     RuleExpressionInfo info;
     bool flag;
     CodeDirectionExpression expression2 = (CodeDirectionExpression) expression;
     if (isWritten)
     {
         ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, new object[] { typeof(CodeDirectionExpression).ToString() }), 0x17a);
         item.UserData["ErrorObject"] = expression2;
         validation.Errors.Add(item);
         return null;
     }
     if (expression2.Expression == null)
     {
         ValidationError error2 = new ValidationError(Messages.NullDirectionTarget, 0x53d);
         error2.UserData["ErrorObject"] = expression2;
         validation.Errors.Add(error2);
         return null;
     }
     if (expression2.Expression is CodeTypeReferenceExpression)
     {
         ValidationError error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CodeExpressionNotHandled, new object[] { expression2.Expression.GetType().FullName }), 0x548);
         error.UserData["ErrorObject"] = expression2.Expression;
         validation.AddError(error);
         return null;
     }
     if (expression2.Direction == FieldDirection.Ref)
     {
         flag = true;
         if (RuleExpressionWalker.Validate(validation, expression2.Expression, false) == null)
         {
             return null;
         }
         info = RuleExpressionWalker.Validate(validation, expression2.Expression, true);
     }
     else if (expression2.Direction == FieldDirection.Out)
     {
         flag = true;
         info = RuleExpressionWalker.Validate(validation, expression2.Expression, true);
     }
     else
     {
         flag = false;
         info = RuleExpressionWalker.Validate(validation, expression2.Expression, false);
     }
     if (info == null)
     {
         return null;
     }
     Type expressionType = info.ExpressionType;
     if (expressionType == null)
     {
         return null;
     }
     if (((expressionType != typeof(NullLiteral)) && flag) && !expressionType.IsByRef)
     {
         expressionType = expressionType.MakeByRefType();
     }
     return new RuleExpressionInfo(expressionType);
 }
		// Methods
		public override bool Evaluate (Activity activity, IServiceProvider provider)
		{

			Activity parent = activity;
			RuleDefinitions definitions = null;

			while (parent != null) {

				definitions = (RuleDefinitions) parent.GetValue (RuleDefinitions.RuleDefinitionsProperty);

				if (definitions != null)
					break;

				parent = parent.Parent;
			}

			if (definitions == null) {
				Console.WriteLine ("No definition");
				return false;
			}

			//Console.WriteLine ("Definition {0} at {1}", definitions, parent);
			RuleValidation validation = new RuleValidation (activity.GetType (), null);
			RuleExecution execution = new RuleExecution (validation, parent);
			RuleCondition condition = definitions.Conditions [ConditionName];
			//Console.WriteLine ("Condition {0}", condition);
			return condition.Evaluate (execution);
		}
示例#3
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ExternalRuleSetService.ExternalRuleSetService ruleSetService = context.GetService<ExternalRuleSetService.ExternalRuleSetService>();

            if (ruleSetService != null)
            {
                RuleSet ruleSet = ruleSetService.GetRuleSet(new RuleSetInfo(this.RuleSetName, this.MajorVersion, this.MinorVersion));
                if (ruleSet != null)
                {
                    Activity targetActivity = this.GetRootWorkflow(this.Parent);
                    RuleValidation validation = new RuleValidation(targetActivity.GetType(), null);
                    RuleExecution execution = new RuleExecution(validation, targetActivity, context);
                    ruleSet.Execute(execution);
                }
            }
            else
            {
                throw new InvalidOperationException("A RuleSetService must be configured on the host to use the PolicyFromService activity.");
            }

            return ActivityExecutionStatus.Closed;
        }
 internal override bool Validate(RuleValidation validation, MemberInfo member, Type contextType, ParameterInfo[] parameters)
 {
     Stack<MemberInfo> methodStack = new Stack<MemberInfo>();
     methodStack.Push(member);
     bool flag = this.ValidateInvokeAttribute(validation, member, contextType, methodStack);
     methodStack.Pop();
     return flag;
 }
 internal override bool Validate(RuleValidation validation)
 {
     bool flag = false;
     RuleExpressionInfo info = null;
     if (this.assignStatement.Left == null)
     {
         ValidationError item = new ValidationError(Messages.NullAssignLeft, 0x541);
         item.UserData["ErrorObject"] = this.assignStatement;
         validation.Errors.Add(item);
     }
     else
     {
         info = validation.ExpressionInfo(this.assignStatement.Left);
         if (info == null)
         {
             info = RuleExpressionWalker.Validate(validation, this.assignStatement.Left, true);
         }
     }
     RuleExpressionInfo info2 = null;
     if (this.assignStatement.Right == null)
     {
         ValidationError error2 = new ValidationError(Messages.NullAssignRight, 0x543);
         error2.UserData["ErrorObject"] = this.assignStatement;
         validation.Errors.Add(error2);
     }
     else
     {
         info2 = RuleExpressionWalker.Validate(validation, this.assignStatement.Right, false);
     }
     if ((info == null) || (info2 == null))
     {
         return flag;
     }
     Type expressionType = info2.ExpressionType;
     Type lhsType = info.ExpressionType;
     if (lhsType == typeof(NullLiteral))
     {
         ValidationError error3 = new ValidationError(Messages.NullAssignLeft, 0x542);
         error3.UserData["ErrorObject"] = this.assignStatement;
         validation.Errors.Add(error3);
         return false;
     }
     if (lhsType != expressionType)
     {
         ValidationError error = null;
         if (!RuleValidation.TypesAreAssignable(expressionType, lhsType, this.assignStatement.Right, out error))
         {
             if (error == null)
             {
                 error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.AssignNotAllowed, new object[] { RuleDecompiler.DecompileType(expressionType), RuleDecompiler.DecompileType(lhsType) }), 0x545);
             }
             error.UserData["ErrorObject"] = this.assignStatement;
             validation.Errors.Add(error);
             return flag;
         }
     }
     return true;
 }
 public override ICollection<string> GetSideEffects(RuleValidation validation)
 {
     RuleAnalysis analysis = new RuleAnalysis(validation, true);
     if (this.codeDomStatement != null)
     {
         CodeDomStatementWalker.AnalyzeUsage(analysis, this.codeDomStatement);
     }
     return analysis.GetSymbols();
 }
 public override ICollection<string> GetDependencies(RuleValidation validation)
 {
     RuleAnalysis analysis = new RuleAnalysis(validation, false);
     if (this._expression != null)
     {
         RuleExpressionWalker.AnalyzeUsage(analysis, this._expression, true, false, null);
     }
     return analysis.GetSymbols();
 }
 private bool ValidateInvokeAttribute(RuleValidation validation, MemberInfo member, Type contextType, Stack<MemberInfo> methodStack)
 {
     ValidationError error;
     if (string.IsNullOrEmpty(this.methodInvoked))
     {
         error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.AttributeMethodNotFound, new object[] { member.Name, base.GetType().Name, Messages.NullValue }), 0x56b, true);
         error.UserData["ErrorObject"] = this;
         validation.AddError(error);
         return false;
     }
     bool flag = true;
     MemberInfo[] infoArray = contextType.GetMember(this.methodInvoked, MemberTypes.Property | MemberTypes.Method, BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
     if ((infoArray == null) || (infoArray.Length == 0))
     {
         error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.AttributeMethodNotFound, new object[] { member.Name, base.GetType().Name, this.methodInvoked }), 0x56b, true);
         error.UserData["ErrorObject"] = this;
         validation.AddError(error);
         return false;
     }
     for (int i = 0; i < infoArray.Length; i++)
     {
         MemberInfo item = infoArray[i];
         if (!methodStack.Contains(item))
         {
             methodStack.Push(item);
             object[] customAttributes = item.GetCustomAttributes(typeof(RuleAttribute), true);
             if ((customAttributes != null) && (customAttributes.Length != 0))
             {
                 foreach (RuleAttribute attribute in customAttributes)
                 {
                     RuleReadWriteAttribute attribute2 = attribute as RuleReadWriteAttribute;
                     if (attribute2 != null)
                     {
                         if (attribute2.Target == RuleAttributeTarget.Parameter)
                         {
                             error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.InvokeAttrRefersToParameterAttribute, new object[] { item.Name }), 0x1a5, true);
                             error.UserData["ErrorObject"] = this;
                             validation.AddError(error);
                             flag = false;
                         }
                         else
                         {
                             attribute2.Validate(validation, item, contextType, null);
                         }
                     }
                     else
                     {
                         ((RuleInvokeAttribute) attribute).ValidateInvokeAttribute(validation, item, contextType, methodStack);
                     }
                 }
             }
             methodStack.Pop();
         }
     }
     return flag;
 }
 internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
 {
     if (isWritten)
     {
         ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, new object[] { typeof(CodeThisReferenceExpression).ToString() }), 0x17a);
         item.UserData["ErrorObject"] = expression;
         validation.Errors.Add(item);
         return null;
     }
     return new RuleExpressionInfo(validation.ThisType);
 }
 public RuleConditionDialog(System.Type activityType, ITypeProvider typeProvider, CodeExpression expression)
 {
     this.ruleExpressionCondition = new RuleExpressionCondition();
     if (activityType == null)
     {
         throw new ArgumentNullException("activityType");
     }
     this.InitializeComponent();
     RuleValidation validation = new RuleValidation(activityType, typeProvider);
     this.ruleParser = new Parser(validation);
     this.InitializeDialog(expression);
 }
 internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
 {
     if (isWritten)
     {
         ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, new object[] { typeof(CodePrimitiveExpression).ToString() }), 0x17a);
         item.UserData["ErrorObject"] = expression;
         validation.Errors.Add(item);
         return null;
     }
     CodePrimitiveExpression expression2 = (CodePrimitiveExpression) expression;
     return new RuleExpressionInfo((expression2.Value != null) ? expression2.Value.GetType() : typeof(NullLiteral));
 }
示例#12
0
        internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
        {
            if (isWritten)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, typeof(CodeThisReferenceExpression).ToString());
                ValidationError error = new ValidationError(message, ErrorNumbers.Error_InvalidAssignTarget);
                error.UserData[RuleUserDataKeys.ErrorObject] = expression;
                validation.Errors.Add(error);
                return null;
            }

            return new RuleExpressionInfo(validation.ThisType);
        }
示例#13
0
        internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
        {
            if (isWritten)
            {
                ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, new object[] { typeof(CodePrimitiveExpression).ToString() }), 0x17a);
                item.UserData["ErrorObject"] = expression;
                validation.Errors.Add(item);
                return(null);
            }
            CodePrimitiveExpression expression2 = (CodePrimitiveExpression)expression;

            return(new RuleExpressionInfo((expression2.Value != null) ? expression2.Value.GetType() : typeof(NullLiteral)));
        }
示例#14
0
        internal static object AdjustTypeWithCast(Type operandType, object operandValue, Type toType)
        {
            // if no conversion required, we are done
            if (operandType == toType)
            {
                return(operandValue);
            }

            if (AdjustValueStandard(operandType, operandValue, toType, out object converted))
            {
                return(converted);
            }

            // handle enumerations (done above?)

            // now it's time for implicit and explicit user defined conversions
            MethodInfo conversion = RuleValidation.FindExplicitConversion(operandType, toType, out ValidationError error);

            if (conversion == null)
            {
                if (error != null)
                {
                    throw new RuleEvaluationException(error.ErrorText);
                }

                throw new RuleEvaluationException(
                          string.Format(CultureInfo.CurrentCulture,
                                        Messages.CastIncompatibleTypes,
                                        RuleDecompiler.DecompileType(operandType),
                                        RuleDecompiler.DecompileType(toType)));
            }

            // now we have a method, need to do the conversion S -> Sx -> Tx -> T
            Type sx = conversion.GetParameters()[0].ParameterType;
            Type tx = conversion.ReturnType;

            if (AdjustValueStandard(operandType, operandValue, sx, out object intermediateResult1))
            {
                // we are happy with the first conversion, so call the user's static method
                object intermediateResult2 = conversion.Invoke(null, new object[] { intermediateResult1 });
                if (AdjustValueStandard(tx, intermediateResult2, toType, out object intermediateResult3))
                {
                    return(intermediateResult3);
                }
            }
            throw new RuleEvaluationException(
                      string.Format(CultureInfo.CurrentCulture,
                                    Messages.CastIncompatibleTypes,
                                    RuleDecompiler.DecompileType(operandType),
                                    RuleDecompiler.DecompileType(toType)));
        }
示例#15
0
        public override bool Evaluate(Activity activity, IServiceProvider provider)
        {
            if (activity == null)
            {
                throw new ArgumentNullException("activity");
            }
            if (string.IsNullOrEmpty(this._condition))
            {
                throw new InvalidOperationException(SR.GetString(SR.Error_MissingConditionName, activity.Name));
            }

            RuleDefinitions defs = null;

            if (string.IsNullOrEmpty(this.declaringActivityId))
            {
                // No Runtime Initialization.
                CompositeActivity declaringActivity = null;
                defs = RuleConditionReference.GetRuleDefinitions(activity, out declaringActivity);
            }
            else
            {
                // Runtime Initialized.
                defs = (RuleDefinitions)activity.GetActivityByName(declaringActivityId).GetValue(RuleDefinitions.RuleDefinitionsProperty);
            }

            if ((defs == null) || (defs.Conditions == null))
            {
                throw new InvalidOperationException(SR.GetString(SR.Error_MissingRuleConditions));
            }

            RuleCondition conditionDefinitionToEvaluate = defs.Conditions[this._condition];

            if (conditionDefinitionToEvaluate != null)
            {
                Activity       contextActivity = System.Workflow.Activities.Common.Helpers.GetEnclosingActivity(activity);
                RuleValidation validation      = new RuleValidation(contextActivity);
                if (!conditionDefinitionToEvaluate.Validate(validation))
                {
                    string message = string.Format(CultureInfo.CurrentCulture, Messages.ConditionValidationFailed, this._condition);
                    throw new InvalidOperationException(message);
                }

                RuleExecution context = new RuleExecution(validation, contextActivity, provider as ActivityExecutionContext);
                return(conditionDefinitionToEvaluate.Evaluate(context));
            }
            else
            {
                // no condition, so defaults to true
                return(true);
            }
        }
        public static RuleExpressionInfo Validate(RuleValidation validation, CodeExpression expression, bool isWritten)
        {
            if (validation == null)
            {
                throw new ArgumentNullException("validation");
            }

            // See if we've visited this node before.
            // Always check if written = true
            RuleExpressionInfo resultExprInfo = null;

            if (!isWritten)
            {
                resultExprInfo = validation.ExpressionInfo(expression);
            }
            if (resultExprInfo == null)
            {
                // First time we've seen this node.
                RuleExpressionInternal ruleExpr = GetExpression(expression);
                if (ruleExpr == null)
                {
                    string          message = string.Format(CultureInfo.CurrentCulture, Messages.CodeExpressionNotHandled, expression.GetType().FullName);
                    ValidationError error   = new ValidationError(message, ErrorNumbers.Error_CodeExpressionNotHandled);
                    error.UserData[RuleUserDataKeys.ErrorObject] = expression;

                    if (validation.Errors == null)
                    {
                        string typeName = string.Empty;
                        if ((validation.ThisType != null) && (validation.ThisType.Name != null))
                        {
                            typeName = validation.ThisType.Name;
                        }

                        string exceptionMessage = string.Format(
                            CultureInfo.CurrentCulture, Messages.ErrorsCollectionMissing, typeName);

                        throw new InvalidOperationException(exceptionMessage);
                    }
                    else
                    {
                        validation.Errors.Add(error);
                    }

                    return(null);
                }

                resultExprInfo = validation.ValidateSubexpression(expression, ruleExpr, isWritten);
            }

            return(resultExprInfo);
        }
示例#17
0
        internal void SetConstructorCompletions(Type computedType, Type thisType)
        {
            BindingFlags constructorBindingFlags = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance;

            if (computedType.Assembly == thisType.Assembly)
            {
                constructorBindingFlags |= BindingFlags.NonPublic;
            }
            List <Type> targetTypes = new List <Type>(1)
            {
                computedType
            };

            this.completions = RuleValidation.GetConstructors(targetTypes, constructorBindingFlags);
        }
 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 override bool Validate(RuleValidation validator)
 {
     if (validator == null)
     {
         throw new ArgumentNullException("validator");
     }
     if (this.codeDomStatement == null)
     {
         ValidationError error = new ValidationError(Messages.NullStatement, 0x53d);
         error.UserData["ErrorObject"] = this;
         validator.AddError(error);
         return false;
     }
     return CodeDomStatementWalker.Validate(validator, this.codeDomStatement);
 }
示例#20
0
 public override bool Validate(RuleValidation validator)
 {
     if (validator == null)
     {
         throw new ArgumentNullException("validator");
     }
     if (this.codeDomStatement == null)
     {
         ValidationError error = new ValidationError(Messages.NullStatement, 0x53d);
         error.UserData["ErrorObject"] = this;
         validator.AddError(error);
         return(false);
     }
     return(CodeDomStatementWalker.Validate(validator, this.codeDomStatement));
 }
        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);
        }
示例#22
0
        internal void SetMethodCompletions(Type computedType, Type thisType, string methodName, bool includeStatic, bool includeInstance, RuleValidation validation)
        {
            BindingFlags @public = BindingFlags.Public;

            if (computedType.Assembly == thisType.Assembly)
            {
                @public |= BindingFlags.NonPublic;
            }
            if (includeInstance)
            {
                @public |= BindingFlags.Instance;
            }
            if (includeStatic)
            {
                @public |= BindingFlags.FlattenHierarchy | BindingFlags.Static;
            }
            List <MemberInfo> candidateMethods = new List <MemberInfo>();

            MemberInfo[] methods = computedType.GetMember(methodName, MemberTypes.Method, @public);
            AddCandidates(candidateMethods, methods);
            if (computedType.IsInterface)
            {
                List <Type> list2 = new List <Type>();
                list2.AddRange(computedType.GetInterfaces());
                for (int i = 0; i < list2.Count; i++)
                {
                    methods = list2[i].GetMember(methodName, MemberTypes.Method, @public);
                    AddCandidates(candidateMethods, methods);
                    Type[] interfaces = list2[i].GetInterfaces();
                    if (interfaces.Length > 0)
                    {
                        list2.AddRange(interfaces);
                    }
                }
                methods = typeof(object).GetMember(methodName, MemberTypes.Method, @public);
                AddCandidates(candidateMethods, methods);
            }
            foreach (ExtensionMethodInfo info in validation.ExtensionMethods)
            {
                ValidationError error;
                if ((info.Name == methodName) && RuleValidation.TypesAreAssignable(computedType, info.AssumedDeclaringType, null, out error))
                {
                    candidateMethods.Add(info);
                }
            }
            this.completions = candidateMethods;
        }
        public override bool Validate(RuleValidation validation)
        {
            if (validation == null)
            {
                throw new ArgumentNullException("validation");
            }
            bool flag = true;

            if (this._expression == null)
            {
                flag = false;
                ValidationError error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.ConditionExpressionNull, new object[] { typeof(CodePrimitiveExpression).ToString() }), 400);
                error.UserData["ErrorObject"] = this;
                validation.AddError(error);
                return(flag);
            }
            return(validation.ValidateConditionExpression(this._expression));
        }
 internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
 {
     CodeTypeReferenceExpression expression2 = (CodeTypeReferenceExpression) expression;
     if (expression2.Type == null)
     {
         ValidationError item = new ValidationError(Messages.NullTypeType, 0x53d);
         item.UserData["ErrorObject"] = expression2;
         validation.Errors.Add(item);
         return null;
     }
     if (isWritten)
     {
         ValidationError error2 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, new object[] { typeof(CodeTypeReferenceExpression).ToString() }), 0x17a);
         error2.UserData["ErrorObject"] = expression2;
         validation.Errors.Add(error2);
         return null;
     }
     return new RuleExpressionInfo(validation.ResolveType(expression2.Type));
 }
示例#25
0
        public override bool Validate(RuleValidation validator)
        {
            if (validator == null)
            {
                throw new ArgumentNullException("validator");
            }

            if (codeDomStatement == null)
            {
                ValidationError error = new ValidationError(Messages.NullStatement, ErrorNumbers.Error_ParameterNotSet);
                error.UserData[RuleUserDataKeys.ErrorObject] = this;
                validator.AddError(error);
                return(false);
            }
            else
            {
                return(CodeDomStatementWalker.Validate(validator, codeDomStatement));
            }
        }
        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);
        }
示例#27
0
 public RuleExecution(RuleValidation validation, object thisObject)
 {
     if (validation == null)
     {
         throw new ArgumentNullException("validation");
     }
     if (thisObject == null)
     {
         throw new ArgumentNullException("thisObject");
     }
     if (validation.ThisType != thisObject.GetType())
     {
         throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ValidationMismatch, new object[] { RuleDecompiler.DecompileType(validation.ThisType), RuleDecompiler.DecompileType(thisObject.GetType()) }));
     }
     this.validation        = validation;
     this.activity          = thisObject as System.Workflow.ComponentModel.Activity;
     this.thisObject        = thisObject;
     this.thisLiteralResult = new RuleLiteralResult(thisObject);
 }
 public RuleExecution(RuleValidation validation, object thisObject)
 {
     if (validation == null)
     {
         throw new ArgumentNullException("validation");
     }
     if (thisObject == null)
     {
         throw new ArgumentNullException("thisObject");
     }
     if (validation.ThisType != thisObject.GetType())
     {
         throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ValidationMismatch, new object[] { RuleDecompiler.DecompileType(validation.ThisType), RuleDecompiler.DecompileType(thisObject.GetType()) }));
     }
     this.validation = validation;
     this.activity = thisObject as System.Workflow.ComponentModel.Activity;
     this.thisObject = thisObject;
     this.thisLiteralResult = new RuleLiteralResult(thisObject);
 }
示例#29
0
        public override bool Evaluate(Activity activity, IServiceProvider provider)
        {
            if (activity == null)
            {
                throw new ArgumentNullException("activity");
            }
            if (string.IsNullOrEmpty(this._condition))
            {
                throw new InvalidOperationException(SR.GetString("Error_MissingConditionName", new object[] { activity.Name }));
            }
            RuleDefinitions ruleDefinitions = null;

            if (string.IsNullOrEmpty(this.declaringActivityId))
            {
                CompositeActivity declaringActivity = null;
                ruleDefinitions = GetRuleDefinitions(activity, out declaringActivity);
            }
            else
            {
                ruleDefinitions = (RuleDefinitions)activity.GetActivityByName(this.declaringActivityId).GetValue(RuleDefinitions.RuleDefinitionsProperty);
            }
            if ((ruleDefinitions == null) || (ruleDefinitions.Conditions == null))
            {
                throw new InvalidOperationException(SR.GetString("Error_MissingRuleConditions"));
            }
            RuleCondition condition = ruleDefinitions.Conditions[this._condition];

            if (condition == null)
            {
                return(true);
            }
            Activity       enclosingActivity = Helpers.GetEnclosingActivity(activity);
            RuleValidation validation        = new RuleValidation(enclosingActivity);

            if (!condition.Validate(validation))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ConditionValidationFailed, new object[] { this._condition }));
            }
            RuleExecution execution = new RuleExecution(validation, enclosingActivity, provider as ActivityExecutionContext);

            return(condition.Evaluate(execution));
        }
示例#30
0
        internal void Validate(RuleValidation validation)
        {
            int count = validation.Errors.Count;

            if (string.IsNullOrEmpty(this.name))
            {
                validation.Errors.Add(new ValidationError(Messages.RuleNameMissing, 0x540));
            }
            if (this.condition == null)
            {
                validation.Errors.Add(new ValidationError(Messages.MissingRuleCondition, 0x57d));
            }
            else
            {
                this.condition.Validate(validation);
            }
            if (this.thenActions != null)
            {
                ValidateRuleActions(this.thenActions, validation);
            }
            if (this.elseActions != null)
            {
                ValidateRuleActions(this.elseActions, validation);
            }
            ValidationErrorCollection errors = validation.Errors;

            if (errors.Count > count)
            {
                string str  = string.Format(CultureInfo.CurrentCulture, Messages.RuleValidationError, new object[] { this.name });
                int    num2 = errors.Count;
                for (int i = count; i < num2; i++)
                {
                    ValidationError error  = errors[i];
                    ValidationError error2 = new ValidationError(str + error.ErrorText, error.ErrorNumber, error.IsWarning);
                    foreach (DictionaryEntry entry in error.UserData)
                    {
                        error2.UserData[entry.Key] = entry.Value;
                    }
                    errors[i] = error2;
                }
            }
        }
示例#31
0
        internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
        {
            CodeTypeReferenceExpression expression2 = (CodeTypeReferenceExpression)expression;

            if (expression2.Type == null)
            {
                ValidationError item = new ValidationError(Messages.NullTypeType, 0x53d);
                item.UserData["ErrorObject"] = expression2;
                validation.Errors.Add(item);
                return(null);
            }
            if (isWritten)
            {
                ValidationError error2 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, new object[] { typeof(CodeTypeReferenceExpression).ToString() }), 0x17a);
                error2.UserData["ErrorObject"] = expression2;
                validation.Errors.Add(error2);
                return(null);
            }
            return(new RuleExpressionInfo(validation.ResolveType(expression2.Type)));
        }
 public RuleConditionDialog(Activity activity, CodeExpression expression)
 {
     ITypeProvider provider;
     this.ruleExpressionCondition = new RuleExpressionCondition();
     if (activity == null)
     {
         throw new ArgumentNullException("activity");
     }
     this.InitializeComponent();
     this.serviceProvider = activity.Site;
     if (this.serviceProvider != null)
     {
         IUIService service = this.serviceProvider.GetService(typeof(IUIService)) as IUIService;
         if (service != null)
         {
             this.Font = (Font) service.Styles["DialogFont"];
         }
         provider = (ITypeProvider) this.serviceProvider.GetService(typeof(ITypeProvider));
         if (provider == null)
         {
             throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.MissingService, new object[] { typeof(ITypeProvider).FullName }));
         }
         WorkflowDesignerLoader loader = this.serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;
         if (loader != null)
         {
             loader.Flush();
         }
     }
     else
     {
         TypeProvider provider2 = new TypeProvider(null);
         foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
         {
             provider2.AddAssembly(assembly);
         }
         provider = provider2;
     }
     RuleValidation validation = new RuleValidation(activity, provider, false);
     this.ruleParser = new Parser(validation);
     this.InitializeDialog(expression);
 }
        internal override bool Validate(RuleValidation validation)
        {
            bool flag = false;

            if (this.exprStatement.Expression == null)
            {
                ValidationError error = new ValidationError(Messages.NullInvokeStatementExpression, 0x53d);
                error.UserData["ErrorObject"] = this.exprStatement;
                validation.Errors.Add(error);
                return(flag);
            }
            if (this.exprStatement.Expression is CodeMethodInvokeExpression)
            {
                return(RuleExpressionWalker.Validate(validation, this.exprStatement.Expression, false) != null);
            }
            ValidationError item = new ValidationError(Messages.InvokeNotHandled, 0x548);

            item.UserData["ErrorObject"] = this.exprStatement;
            validation.Errors.Add(item);
            return(flag);
        }
 public override bool Evaluate(Activity activity, IServiceProvider provider)
 {
     if (activity == null)
     {
         throw new ArgumentNullException("activity");
     }
     if (string.IsNullOrEmpty(this._condition))
     {
         throw new InvalidOperationException(SR.GetString("Error_MissingConditionName", new object[] { activity.Name }));
     }
     RuleDefinitions ruleDefinitions = null;
     if (string.IsNullOrEmpty(this.declaringActivityId))
     {
         CompositeActivity declaringActivity = null;
         ruleDefinitions = GetRuleDefinitions(activity, out declaringActivity);
     }
     else
     {
         ruleDefinitions = (RuleDefinitions) activity.GetActivityByName(this.declaringActivityId).GetValue(RuleDefinitions.RuleDefinitionsProperty);
     }
     if ((ruleDefinitions == null) || (ruleDefinitions.Conditions == null))
     {
         throw new InvalidOperationException(SR.GetString("Error_MissingRuleConditions"));
     }
     RuleCondition condition = ruleDefinitions.Conditions[this._condition];
     if (condition == null)
     {
         return true;
     }
     Activity enclosingActivity = Helpers.GetEnclosingActivity(activity);
     RuleValidation validation = new RuleValidation(enclosingActivity);
     if (!condition.Validate(validation))
     {
         throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ConditionValidationFailed, new object[] { this._condition }));
     }
     RuleExecution execution = new RuleExecution(validation, enclosingActivity, provider as ActivityExecutionContext);
     return condition.Evaluate(execution);
 }
示例#35
0
        internal void Execute(Activity activity, ActivityExecutionContext executionContext)
        {
            // this can be called from multiple threads if multiple workflows are
            // running at the same time (only a single workflow is single-threaded)
            // we want to only lock around the validation and preprocessing, so that
            // execution can run in parallel.

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

            Type       activityType = activity.GetType();
            RuleEngine engine       = null;

            lock (syncLock)
            {
                // do we have something useable cached?
                if ((cachedEngine == null) || (cachedValidation == null) || (cachedValidation.ThisType != activityType))
                {
                    // no cache (or its invalid)
                    RuleValidation validation = new RuleValidation(activityType, null);
                    engine           = new RuleEngine(this, validation, executionContext);
                    cachedValidation = validation;
                    cachedEngine     = engine;
                }
                else
                {
                    // this will happen if the ruleset has already been processed
                    // we can simply use the previously processed engine
                    engine = cachedEngine;
                }
            }

            // when we get here, we have a local RuleEngine all ready to go
            // we are outside the lock, so these can run in parallel
            engine.Execute(activity, executionContext);
        }
示例#36
0
        internal static object AdjustTypeWithCast(Type operandType, object operandValue, Type toType)
        {
            object          obj2;
            ValidationError error;
            object          obj3;

            if (operandType == toType)
            {
                return(operandValue);
            }
            if (AdjustValueStandard(operandType, operandValue, toType, out obj2))
            {
                return(obj2);
            }
            MethodInfo info = RuleValidation.FindExplicitConversion(operandType, toType, out error);

            if (info == null)
            {
                if (error != null)
                {
                    throw new RuleEvaluationException(error.ErrorText);
                }
                throw new RuleEvaluationException(string.Format(CultureInfo.CurrentCulture, Messages.CastIncompatibleTypes, new object[] { RuleDecompiler.DecompileType(operandType), RuleDecompiler.DecompileType(toType) }));
            }
            Type parameterType = info.GetParameters()[0].ParameterType;
            Type returnType    = info.ReturnType;

            if (AdjustValueStandard(operandType, operandValue, parameterType, out obj3))
            {
                object obj5;
                object obj4 = info.Invoke(null, new object[] { obj3 });
                if (AdjustValueStandard(returnType, obj4, toType, out obj5))
                {
                    return(obj5);
                }
            }
            throw new RuleEvaluationException(string.Format(CultureInfo.CurrentCulture, Messages.CastIncompatibleTypes, new object[] { RuleDecompiler.DecompileType(operandType), RuleDecompiler.DecompileType(toType) }));
        }
示例#37
0
        public bool Validate(RuleValidation validation)
        {
            if (validation == null)
            {
                throw new ArgumentNullException("validation");
            }

            // Validate each rule.
            Dictionary <string, object> ruleNames = new Dictionary <string, object>();

            foreach (Rule r in rules)
            {
                if (!string.IsNullOrEmpty(r.Name))  // invalid names caught when validating the rule
                {
                    if (ruleNames.ContainsKey(r.Name))
                    {
                        // Duplicate rule name found.
                        ValidationError error = new ValidationError(Messages.Error_DuplicateRuleName, ErrorNumbers.Error_DuplicateConditions);
                        error.UserData[RuleUserDataKeys.ErrorObject] = r;
                        validation.AddError(error);
                    }
                    else
                    {
                        ruleNames.Add(r.Name, null);
                    }
                }

                r.Validate(validation);
            }

            if (validation.Errors == null || validation.Errors.Count == 0)
            {
                return(true);
            }

            return(false);
        }
示例#38
0
        public static RuleExpressionInfo Validate(RuleValidation validation, CodeExpression expression, bool isWritten)
        {
            if (validation == null)
            {
                throw new ArgumentNullException("validation");
            }
            RuleExpressionInfo info = null;

            if (!isWritten)
            {
                info = validation.ExpressionInfo(expression);
            }
            if (info != null)
            {
                return(info);
            }
            RuleExpressionInternal ruleExpr = GetExpression(expression);

            if (ruleExpr == null)
            {
                ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CodeExpressionNotHandled, new object[] { expression.GetType().FullName }), 0x548);
                item.UserData["ErrorObject"] = expression;
                if (validation.Errors == null)
                {
                    string name = string.Empty;
                    if ((validation.ThisType != null) && (validation.ThisType.Name != null))
                    {
                        name = validation.ThisType.Name;
                    }
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ErrorsCollectionMissing, new object[] { name }));
                }
                validation.Errors.Add(item);
                return(null);
            }
            return(validation.ValidateSubexpression(expression, ruleExpr, isWritten));
        }
示例#39
0
        internal override bool Validate(RuleValidation validation)
        {
            bool success = false;

            if (exprStatement.Expression == null)
            {
                ValidationError error = new ValidationError(Messages.NullInvokeStatementExpression, ErrorNumbers.Error_ParameterNotSet);
                error.UserData[RuleUserDataKeys.ErrorObject] = exprStatement;
                validation.Errors.Add(error);
            }
            else if (exprStatement.Expression is CodeMethodInvokeExpression)
            {
                RuleExpressionInfo exprInfo = RuleExpressionWalker.Validate(validation, exprStatement.Expression, false);
                success = (exprInfo != null);
            }
            else
            {
                ValidationError error = new ValidationError(Messages.InvokeNotHandled, ErrorNumbers.Error_CodeExpressionNotHandled);
                error.UserData[RuleUserDataKeys.ErrorObject] = exprStatement;
                validation.Errors.Add(error);
            }

            return success;
        }
        internal override bool Validate(RuleValidation validation)
        {
            bool success = false;

            if (exprStatement.Expression == null)
            {
                ValidationError error = new ValidationError(Messages.NullInvokeStatementExpression, ErrorNumbers.Error_ParameterNotSet);
                error.UserData[RuleUserDataKeys.ErrorObject] = exprStatement;
                validation.Errors.Add(error);
            }
            else if (exprStatement.Expression is CodeMethodInvokeExpression)
            {
                RuleExpressionInfo exprInfo = RuleExpressionWalker.Validate(validation, exprStatement.Expression, false);
                success = (exprInfo != null);
            }
            else
            {
                ValidationError error = new ValidationError(Messages.InvokeNotHandled, ErrorNumbers.Error_CodeExpressionNotHandled);
                error.UserData[RuleUserDataKeys.ErrorObject] = exprStatement;
                validation.Errors.Add(error);
            }

            return(success);
        }
示例#41
0
        public static Rule Deserialize(this RuleContract contract)
        {
            Assembly ruleAssembly = typeof(Rule).Assembly;
            Type parserType = ruleAssembly.GetType("System.Workflow.Activities.Rules.Parser");

            RuleValidation validation = new RuleValidation(typeof(Person), null);
            var internalRuleParser = Activator.CreateInstance(parserType, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { validation }, null);

            var parseConditionMethodInfo = parserType.GetMethod("ParseCondition", BindingFlags.Instance | BindingFlags.NonPublic);
            RuleExpressionCondition condition = parseConditionMethodInfo.Invoke(internalRuleParser, new object[] { contract.Condition }) as RuleExpressionCondition;

            Rule rule = new Rule {
                Name = contract.Name,
                Priority = contract.Priority,
                ReevaluationBehavior = (RuleReevaluationBehavior)Enum.Parse(typeof(RuleReevaluationBehavior), contract.Reevaluation),
                Active = contract.Active,
                Condition = condition,
            };

            var parseSingleStatementMethodInfo = parserType.GetMethod("ParseSingleStatement", BindingFlags.Instance | BindingFlags.NonPublic);

            foreach (string str in contract.ThenActions) {
                RuleAction action = parseSingleStatementMethodInfo.Invoke(internalRuleParser, new object[] { str }) as RuleAction;
                rule.ThenActions.Add(action);
            }

            var parseStatementListMethodInfo = parserType.GetMethod("ParseStatementList", BindingFlags.Instance | BindingFlags.NonPublic);
            IList<RuleAction> elseActions = parseStatementListMethodInfo.Invoke(internalRuleParser, new object[] { string.Join("\n", contract.ElseActions) }) as IList<RuleAction>;
            if (elseActions != null) {
                foreach (RuleAction action in elseActions) {
                    rule.ElseActions.Add(action);
                }
            }

            return rule;
        }
示例#42
0
 internal abstract bool Validate(RuleValidation validation);
示例#43
0
        internal override bool Validate(RuleValidation validation)
        {
            bool success = false;
            string message;
            RuleExpressionInfo lhsExprInfo = null;

            if (assignStatement.Left == null)
            {
                ValidationError error = new ValidationError(Messages.NullAssignLeft, ErrorNumbers.Error_LeftOperandMissing);
                error.UserData[RuleUserDataKeys.ErrorObject] = assignStatement;
                validation.Errors.Add(error);
            }
            else
            {
                lhsExprInfo = validation.ExpressionInfo(assignStatement.Left);
                if (lhsExprInfo == null)
                    lhsExprInfo = RuleExpressionWalker.Validate(validation, assignStatement.Left, true);
            }

            RuleExpressionInfo rhsExprInfo = null;
            if (assignStatement.Right == null)
            {
                ValidationError error = new ValidationError(Messages.NullAssignRight, ErrorNumbers.Error_RightOperandMissing);
                error.UserData[RuleUserDataKeys.ErrorObject] = assignStatement;
                validation.Errors.Add(error);
            }
            else
            {
                rhsExprInfo = RuleExpressionWalker.Validate(validation, assignStatement.Right, false);
            }

            if (lhsExprInfo != null && rhsExprInfo != null)
            {
                Type expressionType = rhsExprInfo.ExpressionType;
                Type assignmentType = lhsExprInfo.ExpressionType;

                if (assignmentType == typeof(NullLiteral))
                {
                    // Can't assign to a null literal.
                    ValidationError error = new ValidationError(Messages.NullAssignLeft, ErrorNumbers.Error_LeftOperandInvalidType);
                    error.UserData[RuleUserDataKeys.ErrorObject] = assignStatement;
                    validation.Errors.Add(error);
                    success = false;
                }
                else if (assignmentType == expressionType)
                {
                    // Easy case, they're both the same type.
                    success = true;
                }
                else
                {
                    // The types aren't the same, but it still might be a legal assignment.
                    ValidationError error = null;
                    if (!RuleValidation.TypesAreAssignable(expressionType, assignmentType, assignStatement.Right, out error))
                    {
                        if (error == null)
                        {
                            message = string.Format(CultureInfo.CurrentCulture, Messages.AssignNotAllowed, RuleDecompiler.DecompileType(expressionType), RuleDecompiler.DecompileType(assignmentType));
                            error = new ValidationError(message, ErrorNumbers.Error_OperandTypesIncompatible);
                        }
                        error.UserData[RuleUserDataKeys.ErrorObject] = assignStatement;
                        validation.Errors.Add(error);
                    }
                    else
                    {
                        success = true;
                    }
                }
            }

            return success;
        }
示例#44
0
        internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
        {
            CodeCastExpression expression2 = (CodeCastExpression)expression;

            if (isWritten)
            {
                ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, new object[] { typeof(CodeCastExpression).ToString() }), 0x17a);
                item.UserData["ErrorObject"] = expression2;
                validation.Errors.Add(item);
                return(null);
            }
            if (expression2.Expression == null)
            {
                ValidationError error2 = new ValidationError(Messages.NullCastExpr, 0x53d);
                error2.UserData["ErrorObject"] = expression2;
                validation.Errors.Add(error2);
                return(null);
            }
            if (expression2.Expression is CodeTypeReferenceExpression)
            {
                ValidationError error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CodeExpressionNotHandled, new object[] { expression2.Expression.GetType().FullName }), 0x548);
                error.UserData["ErrorObject"] = expression2.Expression;
                validation.AddError(error);
                return(null);
            }
            if (expression2.TargetType == null)
            {
                ValidationError error4 = new ValidationError(Messages.NullCastType, 0x53d);
                error4.UserData["ErrorObject"] = expression2;
                validation.Errors.Add(error4);
                return(null);
            }
            RuleExpressionInfo info = RuleExpressionWalker.Validate(validation, expression2.Expression, false);

            if (info == null)
            {
                return(null);
            }
            Type expressionType = info.ExpressionType;
            Type type           = validation.ResolveType(expression2.TargetType);

            if (type == null)
            {
                return(null);
            }
            if (expressionType == typeof(NullLiteral))
            {
                if (ConditionHelper.IsNonNullableValueType(type))
                {
                    ValidationError error5 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CastOfNullInvalid, new object[] { RuleDecompiler.DecompileType(type) }), 0x53d);
                    error5.UserData["ErrorObject"] = expression2;
                    validation.Errors.Add(error5);
                    return(null);
                }
            }
            else
            {
                Type type3 = expressionType;
                if (ConditionHelper.IsNullableValueType(type3))
                {
                    type3 = type3.GetGenericArguments()[0];
                }
                Type type4 = type;
                if (ConditionHelper.IsNullableValueType(type4))
                {
                    type4 = type4.GetGenericArguments()[0];
                }
                bool flag = false;
                if (type3.IsValueType && type4.IsValueType)
                {
                    if (type3.IsEnum)
                    {
                        flag = type4.IsEnum || IsNumeric(type4);
                    }
                    else if (type4.IsEnum)
                    {
                        flag = IsNumeric(type3);
                    }
                    else if (type3 == typeof(char))
                    {
                        flag = IsNumeric(type4);
                    }
                    else if (type4 == typeof(char))
                    {
                        flag = IsNumeric(type3);
                    }
                    else if (type3.IsPrimitive && type4.IsPrimitive)
                    {
                        try
                        {
                            Convert.ChangeType(Activator.CreateInstance(type3), type4, CultureInfo.CurrentCulture);
                            flag = true;
                        }
                        catch (Exception)
                        {
                            flag = false;
                        }
                    }
                }
                if (!flag)
                {
                    ValidationError error6;
                    flag = RuleValidation.ExplicitConversionSpecified(expressionType, type, out error6);
                    if (error6 != null)
                    {
                        error6.UserData["ErrorObject"] = expression2;
                        validation.Errors.Add(error6);
                        return(null);
                    }
                }
                if (!flag)
                {
                    ValidationError error7 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CastIncompatibleTypes, new object[] { RuleDecompiler.DecompileType(expressionType), RuleDecompiler.DecompileType(type) }), 0x53d);
                    error7.UserData["ErrorObject"] = expression2;
                    validation.Errors.Add(error7);
                    return(null);
                }
            }
            return(new RuleExpressionInfo(type));
        }
 public abstract bool Validate(RuleValidation validator);
 public RuleExecution(RuleValidation validation, object thisObject, System.Workflow.ComponentModel.ActivityExecutionContext activityExecutionContext) : this(validation, thisObject)
 {
     this.activityExecutionContext = activityExecutionContext;
 }
        private bool GetThisType(string rulesFileDirectoryPath, string rulesFileName)
        {
            bool successfulLoad = false;

            if (!string.IsNullOrEmpty(rulesFileDirectoryPath) && selectedRuleSetData != null)
            {
                string thisTypeAssemblyPath = rulesFileDirectoryPath + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug";
                if (Directory.Exists(thisTypeAssemblyPath))
                {
                    assemblyPath = thisTypeAssemblyPath;
                    string[] fileNames = Directory.GetFiles(thisTypeAssemblyPath);
                    Dictionary<Type,string> candidateThisTypes = new Dictionary<Type,string>();

                    //try and automatically locate the Type referenced by this ruleset
                    foreach (string fileName in fileNames)
                    {
                        if (fileName.EndsWith("dll", StringComparison.Ordinal) || fileName.EndsWith("exe", StringComparison.Ordinal))
                        {
                            Assembly assembly = null;
                            try
                            {
                                assembly = Assembly.LoadFile(fileName); //this will skip the load if it's already been loaded, which is a problem if you point to a different assembly with the same version number
                            }
                            catch (Exception) //ignore this assembly then
                            {
                            }

                            if (assembly != null)
                            {
                                foreach (Type type in assembly.GetTypes())
                                {
                                    try
                                    {
                                        RuleValidation validation = new RuleValidation(type, null);
                                        if (selectedRuleSetData.RuleSet.Validate(validation))
                                            candidateThisTypes.Add(type,fileName); // type matches the ruleset members
                                    }
                                    catch (Exception) //error creating RuleValidation or doing validation so ignore this type
                                    {
                                    }
                                }
                            }
                        }
                    }

                    if (candidateThisTypes.Count == 0) //no matching types found so prompt the user
                    {
                        successfulLoad = this.PromptForThisType(rulesFileDirectoryPath);
                    }
                    else if (candidateThisTypes.Count == 1) //one matching Type in the assemblies in the default path, so just use it
                    {
                        IEnumerator enumerator = candidateThisTypes.Keys.GetEnumerator();
                        enumerator.MoveNext();
                        selectedRuleSetData.Activity = enumerator.Current as Type;
                        selectedRuleSetData.AssemblyPath = candidateThisTypes[selectedRuleSetData.Activity];
                        successfulLoad = true;
                    }
                    else //more than one matching Type
                    {
                        //see if there is a single Type with the same name as the .rules file
                        Dictionary<Type, string> candidateThisTypesMatchingName = new Dictionary<Type, string>();
                        foreach (Type type in candidateThisTypes.Keys)
                        {
                            if (type.Name == Path.GetFileNameWithoutExtension(rulesFileName))
                                candidateThisTypesMatchingName.Add(type, candidateThisTypes[type]);
                        }
                        if (candidateThisTypesMatchingName.Count == 1)
                        {
                            IEnumerator enumerator = candidateThisTypesMatchingName.Keys.GetEnumerator();
                            enumerator.MoveNext();
                            selectedRuleSetData.Activity = enumerator.Current as Type;
                            selectedRuleSetData.AssemblyPath = candidateThisTypesMatchingName[selectedRuleSetData.Activity];
                            successfulLoad = true;
                        }
                        else
                        {
                            successfulLoad = this.PromptForThisType(thisTypeAssemblyPath);
                        }
                    }
                }
                else
                {
                    successfulLoad = this.PromptForThisType(rulesFileDirectoryPath);
                }
            }
            return successfulLoad;
        }
示例#48
0
 internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
 {
     return(this.ruleExpr.Validate(validation, isWritten));
 }
        internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
        {
            ValidationError error;
            CodeBinaryOperatorExpression newParent = (CodeBinaryOperatorExpression)expression;

            if (!validation.PushParentExpression(newParent))
            {
                return(null);
            }
            if (isWritten)
            {
                error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, new object[] { typeof(CodeBinaryOperatorExpression).ToString() }), 0x17a);
                error.UserData["ErrorObject"] = newParent;
                validation.Errors.Add(error);
            }
            RuleExpressionInfo info  = null;
            RuleExpressionInfo info2 = null;

            if (newParent.Left == null)
            {
                error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.NullBinaryOpLHS, new object[] { newParent.Operator.ToString() }), 0x541);
                error.UserData["ErrorObject"] = newParent;
                validation.Errors.Add(error);
            }
            else
            {
                if (newParent.Left is CodeTypeReferenceExpression)
                {
                    error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CodeExpressionNotHandled, new object[] { newParent.Left.GetType().FullName }), 0x548);
                    error.UserData["ErrorObject"] = newParent.Left;
                    validation.AddError(error);
                    return(null);
                }
                info = RuleExpressionWalker.Validate(validation, newParent.Left, false);
            }
            if (newParent.Right == null)
            {
                error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.NullBinaryOpRHS, new object[] { newParent.Operator.ToString() }), 0x543);
                error.UserData["ErrorObject"] = newParent;
                validation.Errors.Add(error);
            }
            else
            {
                if (newParent.Right is CodeTypeReferenceExpression)
                {
                    error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CodeExpressionNotHandled, new object[] { newParent.Right.GetType().FullName }), 0x548);
                    error.UserData["ErrorObject"] = newParent.Right;
                    validation.AddError(error);
                    return(null);
                }
                info2 = RuleExpressionWalker.Validate(validation, newParent.Right, false);
            }
            validation.PopParentExpression();
            RuleBinaryExpressionInfo info3 = null;

            if ((info != null) && (info2 != null))
            {
                Type expressionType = info.ExpressionType;
                Type rhs            = info2.ExpressionType;
                switch (newParent.Operator)
                {
                case CodeBinaryOperatorType.Add:
                case CodeBinaryOperatorType.Subtract:
                case CodeBinaryOperatorType.Multiply:
                case CodeBinaryOperatorType.Divide:
                case CodeBinaryOperatorType.Modulus:
                case CodeBinaryOperatorType.BitwiseOr:
                case CodeBinaryOperatorType.BitwiseAnd:
                    info3 = ArithmeticLiteral.ResultType(newParent.Operator, expressionType, newParent.Left, rhs, newParent.Right, validation, out error);
                    if (info3 == null)
                    {
                        if ((!(expressionType == typeof(ulong)) || !PromotionPossible(rhs, newParent.Right)) && (!(rhs == typeof(ulong)) || !PromotionPossible(expressionType, newParent.Left)))
                        {
                            error.UserData["ErrorObject"] = newParent;
                            validation.Errors.Add(error);
                        }
                        else
                        {
                            info3 = new RuleBinaryExpressionInfo(expressionType, rhs, typeof(ulong));
                        }
                    }
                    goto Label_063E;

                case CodeBinaryOperatorType.IdentityInequality:
                case CodeBinaryOperatorType.IdentityEquality:
                    info3 = new RuleBinaryExpressionInfo(expressionType, rhs, typeof(bool));
                    goto Label_063E;

                case CodeBinaryOperatorType.ValueEquality:
                    info3 = Literal.AllowedComparison(expressionType, newParent.Left, rhs, newParent.Right, newParent.Operator, validation, out error);
                    if (info3 == null)
                    {
                        if ((!(expressionType == typeof(ulong)) || !PromotionPossible(rhs, newParent.Right)) && (!(rhs == typeof(ulong)) || !PromotionPossible(expressionType, newParent.Left)))
                        {
                            error.UserData["ErrorObject"] = newParent;
                            validation.Errors.Add(error);
                        }
                        else
                        {
                            info3 = new RuleBinaryExpressionInfo(expressionType, rhs, typeof(bool));
                        }
                    }
                    goto Label_063E;

                case CodeBinaryOperatorType.BooleanOr:
                case CodeBinaryOperatorType.BooleanAnd:
                    info3 = new RuleBinaryExpressionInfo(expressionType, rhs, typeof(bool));
                    if (expressionType != typeof(bool))
                    {
                        error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.LogicalOpBadTypeLHS, new object[] { newParent.Operator.ToString(), (expressionType == typeof(NullLiteral)) ? Messages.NullValue : RuleDecompiler.DecompileType(expressionType) }), 0x542);
                        error.UserData["ErrorObject"] = newParent;
                        validation.Errors.Add(error);
                        info3 = null;
                    }
                    if (rhs != typeof(bool))
                    {
                        error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.LogicalOpBadTypeRHS, new object[] { newParent.Operator.ToString(), (rhs == typeof(NullLiteral)) ? Messages.NullValue : RuleDecompiler.DecompileType(rhs) }), 0x544);
                        error.UserData["ErrorObject"] = newParent;
                        validation.Errors.Add(error);
                        info3 = null;
                    }
                    goto Label_063E;

                case CodeBinaryOperatorType.LessThan:
                case CodeBinaryOperatorType.LessThanOrEqual:
                case CodeBinaryOperatorType.GreaterThan:
                case CodeBinaryOperatorType.GreaterThanOrEqual:
                    info3 = Literal.AllowedComparison(expressionType, newParent.Left, rhs, newParent.Right, newParent.Operator, validation, out error);
                    if (info3 == null)
                    {
                        if ((!(expressionType == typeof(ulong)) || !PromotionPossible(rhs, newParent.Right)) && (!(rhs == typeof(ulong)) || !PromotionPossible(expressionType, newParent.Left)))
                        {
                            error.UserData["ErrorObject"] = newParent;
                            validation.Errors.Add(error);
                        }
                        else
                        {
                            info3 = new RuleBinaryExpressionInfo(expressionType, rhs, typeof(bool));
                        }
                    }
                    goto Label_063E;
                }
                error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.BinaryOpNotSupported, new object[] { newParent.Operator.ToString() }), 0x548);
                error.UserData["ErrorObject"] = newParent;
                validation.Errors.Add(error);
            }
Label_063E:
            if (info3 != null)
            {
                MethodInfo methodInfo = info3.MethodInfo;
                if (methodInfo == null)
                {
                    return(info3);
                }
                object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuleAttribute), true);
                if ((customAttributes == null) || (customAttributes.Length <= 0))
                {
                    return(info3);
                }
                Stack <MemberInfo> stack = new Stack <MemberInfo>();
                stack.Push(methodInfo);
                bool flag = true;
                foreach (RuleAttribute attribute in customAttributes)
                {
                    if (!attribute.Validate(validation, methodInfo, methodInfo.DeclaringType, methodInfo.GetParameters()))
                    {
                        flag = false;
                    }
                }
                stack.Pop();
                if (!flag)
                {
                    return(null);
                }
            }
            return(info3);
        }
        internal override bool Validate(RuleValidation validation)
        {
            bool               success = false;
            string             message;
            RuleExpressionInfo lhsExprInfo = null;

            if (assignStatement.Left == null)
            {
                ValidationError error = new ValidationError(Messages.NullAssignLeft, ErrorNumbers.Error_LeftOperandMissing);
                error.UserData[RuleUserDataKeys.ErrorObject] = assignStatement;
                validation.Errors.Add(error);
            }
            else
            {
                lhsExprInfo = validation.ExpressionInfo(assignStatement.Left);
                if (lhsExprInfo == null)
                {
                    lhsExprInfo = RuleExpressionWalker.Validate(validation, assignStatement.Left, true);
                }
            }

            RuleExpressionInfo rhsExprInfo = null;

            if (assignStatement.Right == null)
            {
                ValidationError error = new ValidationError(Messages.NullAssignRight, ErrorNumbers.Error_RightOperandMissing);
                error.UserData[RuleUserDataKeys.ErrorObject] = assignStatement;
                validation.Errors.Add(error);
            }
            else
            {
                rhsExprInfo = RuleExpressionWalker.Validate(validation, assignStatement.Right, false);
            }

            if (lhsExprInfo != null && rhsExprInfo != null)
            {
                Type expressionType = rhsExprInfo.ExpressionType;
                Type assignmentType = lhsExprInfo.ExpressionType;

                if (assignmentType == typeof(NullLiteral))
                {
                    // Can't assign to a null literal.
                    ValidationError error = new ValidationError(Messages.NullAssignLeft, ErrorNumbers.Error_LeftOperandInvalidType);
                    error.UserData[RuleUserDataKeys.ErrorObject] = assignStatement;
                    validation.Errors.Add(error);
                    success = false;
                }
                else if (assignmentType == expressionType)
                {
                    // Easy case, they're both the same type.
                    success = true;
                }
                else
                {
                    // The types aren't the same, but it still might be a legal assignment.
                    if (!RuleValidation.TypesAreAssignable(expressionType, assignmentType, assignStatement.Right, out ValidationError error))
                    {
                        if (error == null)
                        {
                            message = string.Format(CultureInfo.CurrentCulture, Messages.AssignNotAllowed, RuleDecompiler.DecompileType(expressionType), RuleDecompiler.DecompileType(assignmentType));
                            error   = new ValidationError(message, ErrorNumbers.Error_OperandTypesIncompatible);
                        }
                        error.UserData[RuleUserDataKeys.ErrorObject] = assignStatement;
                        validation.Errors.Add(error);
                    }
                    else
                    {
                        success = true;
                    }
                }
            }

            return(success);
        }
 internal abstract bool Validate(RuleValidation validation);
 internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
 {
     CodeFieldReferenceExpression newParent = (CodeFieldReferenceExpression) expression;
     if (newParent.TargetObject == null)
     {
         ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.NullFieldTarget, new object[] { newParent.FieldName }), 0x53d);
         item.UserData["ErrorObject"] = newParent;
         validation.Errors.Add(item);
         return null;
     }
     if (!validation.PushParentExpression(newParent))
     {
         return null;
     }
     RuleExpressionInfo info = RuleExpressionWalker.Validate(validation, newParent.TargetObject, false);
     validation.PopParentExpression();
     if (info == null)
     {
         return null;
     }
     Type expressionType = info.ExpressionType;
     if (expressionType == null)
     {
         return null;
     }
     if (expressionType == typeof(NullLiteral))
     {
         ValidationError error2 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.NullFieldTarget, new object[] { newParent.FieldName }), 0x546);
         error2.UserData["ErrorObject"] = newParent;
         validation.Errors.Add(error2);
         return null;
     }
     BindingFlags @public = BindingFlags.Public;
     if (newParent.TargetObject is CodeTypeReferenceExpression)
     {
         @public |= BindingFlags.FlattenHierarchy | BindingFlags.Static;
     }
     else
     {
         @public |= BindingFlags.Instance;
     }
     if (validation.AllowInternalMembers(expressionType))
     {
         @public |= BindingFlags.NonPublic;
     }
     FieldInfo field = expressionType.GetField(newParent.FieldName, @public);
     if (field == null)
     {
         ValidationError error3 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.UnknownField, new object[] { newParent.FieldName, RuleDecompiler.DecompileType(expressionType) }), 0x54a);
         error3.UserData["ErrorObject"] = newParent;
         validation.Errors.Add(error3);
         return null;
     }
     if (field.FieldType == null)
     {
         ValidationError error4 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CouldNotDetermineMemberType, new object[] { newParent.FieldName }), 0x194);
         error4.UserData["ErrorObject"] = newParent;
         validation.Errors.Add(error4);
         return null;
     }
     if (isWritten && field.IsLiteral)
     {
         ValidationError error5 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.FieldSetNotAllowed, new object[] { newParent.FieldName, RuleDecompiler.DecompileType(expressionType) }), 0x17a);
         error5.UserData["ErrorObject"] = newParent;
         validation.Errors.Add(error5);
         return null;
     }
     if (!validation.ValidateMemberAccess(newParent.TargetObject, expressionType, field, field.Name, newParent))
     {
         return null;
     }
     validation.IsAuthorized(field.FieldType);
     return new RuleFieldExpressionInfo(field);
 }
示例#53
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 abstract ICollection<string> GetSideEffects(RuleValidation validation);
示例#55
0
 public override ICollection<string> GetSideEffects(RuleValidation validation)
 {
     return null;
 }
示例#56
0
        public override bool Validate(RuleValidation validator)
        {
            if (validator == null)
                throw new ArgumentNullException("validator");

            bool success = true;

            if (path == null)
            {
                ValidationError error = new ValidationError(Messages.NullUpdate, ErrorNumbers.Error_ParameterNotSet);
                error.UserData[RuleUserDataKeys.ErrorObject] = this;
                validator.AddError(error);
                success = false;
            }

            // now make sure that the path is valid
            string[] parts = path.Split('/');
            if (parts[0] == "this")
            {
                Type currentType = validator.ThisType;
                for (int i = 1; i < parts.Length; ++i)
                {
                    if (parts[i] == "*")
                    {
                        if (i < parts.Length - 1)
                        {
                            // The "*" occurred in the middle of the path, which is a no-no.
                            ValidationError error = new ValidationError(Messages.InvalidWildCardInPathQualifier, ErrorNumbers.Error_InvalidWildCardInPathQualifier);
                            error.UserData[RuleUserDataKeys.ErrorObject] = this;
                            validator.AddError(error);
                            success = false;
                            break;
                        }
                        else
                        {
                            // It occurred at the end, which is okay.
                            break;
                        }
                    }
                    else if (string.IsNullOrEmpty(parts[i]) && i == parts.Length - 1)
                    {
                        // It's okay to end with a "/".
                        break;
                    }

                    while (currentType.IsArray)
                        currentType = currentType.GetElementType();

                    BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
                    if (validator.AllowInternalMembers(currentType))
                        bindingFlags |= BindingFlags.NonPublic;
                    FieldInfo field = currentType.GetField(parts[i], bindingFlags);
                    if (field != null)
                    {
                        currentType = field.FieldType;
                    }
                    else
                    {
                        PropertyInfo property = currentType.GetProperty(parts[i], bindingFlags);
                        if (property != null)
                        {
                            currentType = property.PropertyType;
                        }
                        else
                        {
                            string message = string.Format(CultureInfo.CurrentCulture, Messages.UpdateUnknownFieldOrProperty, parts[i]);
                            ValidationError error = new ValidationError(message, ErrorNumbers.Error_InvalidUpdate);
                            error.UserData[RuleUserDataKeys.ErrorObject] = this;
                            validator.AddError(error);
                            success = false;
                            break;
                        }
                    }
                }
            }
            else
            {
                ValidationError error = new ValidationError(Messages.UpdateNotThis, ErrorNumbers.Error_InvalidUpdate);
                error.UserData[RuleUserDataKeys.ErrorObject] = this;
                validator.AddError(error);
                success = false;
            }

            return success;
        }
示例#57
0
 public RuleAnalysis(RuleValidation validation, bool forWrites)
 {
     symbols = new List <string> ();
 }
 public abstract ICollection <string> GetSideEffects(RuleValidation validation);
 public abstract bool Validate(RuleValidation validator);
 public RuleEngine(RuleSet ruleSet, RuleValidation validation) : this(ruleSet, validation, null)
 {
 }