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);
 }
 private static void FillCorrelationAliasAttrs(MemberInfo memberInfo, Hashtable correlationAliasAttrs, ValidationErrorCollection validationErrors)
 {
     foreach (object obj2 in memberInfo.GetCustomAttributes(typeof(CorrelationAliasAttribute), false))
     {
         CorrelationAliasAttribute attributeFromObject = Helpers.GetAttributeFromObject<CorrelationAliasAttribute>(obj2);
         if (string.IsNullOrEmpty(attributeFromObject.Name) || (attributeFromObject.Name.Trim().Length == 0))
         {
             ValidationError item = new ValidationError(SR.GetString(CultureInfo.CurrentCulture, "Error_CorrelationAttributeInvalid", new object[] { typeof(CorrelationAliasAttribute).Name, "Name", memberInfo.Name }), 0x150);
             item.UserData.Add(typeof(CorrelationAliasAttribute), memberInfo.Name);
             validationErrors.Add(item);
         }
         else if (string.IsNullOrEmpty(attributeFromObject.Path) || (attributeFromObject.Path.Trim().Length == 0))
         {
             ValidationError error2 = new ValidationError(SR.GetString(CultureInfo.CurrentCulture, "Error_CorrelationAttributeInvalid", new object[] { typeof(CorrelationAliasAttribute).Name, "Path", memberInfo.Name }), 0x150);
             error2.UserData.Add(typeof(CorrelationAliasAttribute), memberInfo.Name);
             validationErrors.Add(error2);
         }
         else if (correlationAliasAttrs.Contains(attributeFromObject.Name))
         {
             ValidationError error3 = new ValidationError(SR.GetString(CultureInfo.CurrentCulture, "Error_DuplicateCorrelationAttribute", new object[] { typeof(CorrelationAliasAttribute).Name, attributeFromObject.Name, memberInfo.Name }), 0x151);
             error3.UserData.Add(typeof(CorrelationAliasAttribute), memberInfo.Name);
             validationErrors.Add(error3);
         }
         else
         {
             correlationAliasAttrs.Add(attributeFromObject.Name, attributeFromObject);
         }
     }
 }
 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;
 }
 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);
 }
 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));
 }
 public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
 {
     ValidationErrorCollection errors = base.Validate(manager, obj);
     MethodBind bind = obj as MethodBind;
     if (bind == null)
     {
         throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(MethodBind).FullName }), "obj");
     }
     PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext;
     if (validationContext == null)
     {
         throw new InvalidOperationException(SR.GetString("Error_ContextStackItemMissing", new object[] { typeof(BindValidationContext).Name }));
     }
     Activity activity = manager.Context[typeof(Activity)] as Activity;
     if (activity == null)
     {
         throw new InvalidOperationException(SR.GetString("Error_ContextStackItemMissing", new object[] { typeof(Activity).Name }));
     }
     ValidationError item = null;
     if (string.IsNullOrEmpty(bind.Name))
     {
         item = new ValidationError(SR.GetString("Error_PropertyNotSet", new object[] { "Name" }), 0x116) {
             PropertyName = base.GetFullPropertyName(manager) + ".Name"
         };
     }
     else
     {
         BindValidationContext context2 = manager.Context[typeof(BindValidationContext)] as BindValidationContext;
         if (context2 == null)
         {
             Type baseType = BindHelpers.GetBaseType(manager, validationContext);
             if (baseType != null)
             {
                 AccessTypes accessType = BindHelpers.GetAccessType(manager, validationContext);
                 context2 = new BindValidationContext(baseType, accessType);
             }
         }
         if (context2 != null)
         {
             Type targetType = context2.TargetType;
             if (item == null)
             {
                 errors.AddRange(this.ValidateMethod(manager, activity, bind, new BindValidationContext(targetType, context2.Access)));
             }
         }
     }
     if (item != null)
     {
         errors.Add(item);
     }
     return errors;
 }
Пример #8
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);
        }
Пример #9
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            FieldBind bind = obj as FieldBind;
            if (bind == null)
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(FieldBind).FullName), "obj");

            PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext;
            if (validationContext == null)
                throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(BindValidationContext).Name));

            Activity activity = manager.Context[typeof(Activity)] as Activity;
            if (activity == null)
                throw new InvalidOperationException(SR.GetString(SR.Error_ContextStackItemMissing, typeof(Activity).Name));

            ValidationError error = null;
            if (string.IsNullOrEmpty(bind.Name))
            {
                error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, "Name"), ErrorNumbers.Error_PropertyNotSet);
                error.PropertyName = GetFullPropertyName(manager) + ".Name";
            }
            else
            {
                BindValidationContext validationBindContext = manager.Context[typeof(BindValidationContext)] as BindValidationContext;
                if (validationBindContext == null)
                {
                    Type baseType = BindHelpers.GetBaseType(manager, validationContext);
                    if (baseType != null)
                    {
                        AccessTypes accessType = BindHelpers.GetAccessType(manager, validationContext);
                        validationBindContext = new BindValidationContext(baseType, accessType);
                    }
                    //else
                    //{
                    //    error = new ValidationError(SR.GetString(SR.Error_BindBaseTypeNotSpecified, validationContext.PropertyName), ErrorNumbers.Error_BindBaseTypeNotSpecified);
                    //    error.PropertyName = GetFullPropertyName(manager) + ".Name";
                    //}
                }
                if (validationBindContext != null)
                {
                    Type targetType = validationBindContext.TargetType;
                    if (error == null)
                        validationErrors.AddRange(this.ValidateField(manager, activity, bind, new BindValidationContext(targetType, validationBindContext.Access)));
                }
            }
            if (error != null)
                validationErrors.Add(error);

            return validationErrors;
        }
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            if (manager == null)
                throw new ArgumentNullException("manager");

            Activity activity = obj as Activity;
            if (activity == null)
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "obj");

            if (manager.Context == null)
                throw new ArgumentException("manager", SR.GetString(SR.Error_MissingContextProperty));

            manager.Context.Push(activity);

            ValidationErrorCollection errors = new ValidationErrorCollection();
            errors.AddRange(base.Validate(manager, obj));

            if (activity.Parent == null)
            {
                errors.AddRange(ValidationHelpers.ValidateUniqueIdentifiers(activity));

                if (activity.Enabled == false)
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_RootIsNotEnabled), ErrorNumbers.Error_RootIsNotEnabled);
                    error.PropertyName = "Enabled";
                    errors.Add(error);
                }
            }

            // validate ID property, only if it is not root activity
            Activity rootActivity = Helpers.GetRootActivity(activity);
            if (activity != rootActivity)
            {
                ValidationError identifierError = ValidationHelpers.ValidateNameProperty("Name", manager, activity.Name);
                if (identifierError != null)
                    errors.Add(identifierError);
            }

            try
            {
                errors.AddRange(ValidateProperties(manager, obj));
            }
            finally
            {
                System.Diagnostics.Debug.Assert(manager.Context.Current == activity, "Unwinding contextStack: the item that is about to be popped is not the one we pushed.");
                manager.Context.Pop();
            }

            return errors;
        }
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection errors = base.Validate(manager, obj);

             MsmqSendActivity act = (MsmqSendActivity)obj;

             if ( !act.IsBindingSet(MsmqSendActivity.QueueProperty) )
             {
            if ( act.GetValue(MsmqSendActivity.QueueProperty) == null )
            {
               errors.Add(ValidationError.GetNotSetValidationError("Queue"));
            }
             }
             if ( !act.IsBindingSet(MsmqSendActivity.MessageToSendProperty) )
             {
            if ( act.GetValue(MsmqSendActivity.MessageToSendProperty) == null )
            {
               errors.Add(ValidationError.GetNotSetValidationError("MessageToSend"));
            }
             }

             // if the queue is transactional, one of our parents
             // must be a TransactionScope
             if ( act.IsTransactionalQueue )
             {
            bool isInTransaction = false;
            Activity parent = act.Parent;

            while ( parent != null )
            {
               if ( parent is TransactionScopeActivity )
               {
                  isInTransaction = true;
                  break;
               }
               parent = parent.Parent;
            }

            if ( !isInTransaction )
            {
               ValidationError error =
                  new ValidationError(Resources.Send_MustBeInTransaction, 9001);
               errors.Add(error);
            }
             }

             return errors;
        }
 public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     Activity context = obj as Activity;
     if (context == null)
     {
         throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(Activity).FullName }), "obj");
     }
     if (manager.Context == null)
     {
         throw new ArgumentException("manager", SR.GetString("Error_MissingContextProperty"));
     }
     manager.Context.Push(context);
     ValidationErrorCollection errors = new ValidationErrorCollection();
     errors.AddRange(base.Validate(manager, obj));
     if (context.Parent == null)
     {
         errors.AddRange(ValidationHelpers.ValidateUniqueIdentifiers(context));
         if (!context.Enabled)
         {
             ValidationError item = new ValidationError(SR.GetString("Error_RootIsNotEnabled"), 0x628) {
                 PropertyName = "Enabled"
             };
             errors.Add(item);
         }
     }
     Activity rootActivity = Helpers.GetRootActivity(context);
     if (context != rootActivity)
     {
         ValidationError error2 = ValidationHelpers.ValidateNameProperty("Name", manager, context.Name);
         if (error2 != null)
         {
             errors.Add(error2);
         }
     }
     try
     {
         errors.AddRange(this.ValidateProperties(manager, obj));
     }
     finally
     {
         manager.Context.Pop();
     }
     return errors;
 }
 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 override ValidationErrorCollection Validate(ValidationManager manager, object obj)
 {
     ValidationErrorCollection errors = base.Validate(manager, obj);
     FaultHandlerActivity activity = obj as FaultHandlerActivity;
     if (activity == null)
     {
         throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(FaultHandlerActivity).FullName }), "obj");
     }
     if (!(activity.Parent is FaultHandlersActivity))
     {
         errors.Add(new ValidationError(SR.GetString("Error_FaultHandlerActivityParentNotFaultHandlersActivity"), 0x519));
     }
     if (!(manager.GetService(typeof(ITypeProvider)) is ITypeProvider))
     {
         throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName }));
     }
     ValidationError item = null;
     if (activity.FaultType == null)
     {
         item = new ValidationError(SR.GetString("Error_TypePropertyInvalid", new object[] { "FaultType" }), 0x116) {
             PropertyName = "FaultType"
         };
         errors.Add(item);
     }
     else if (!TypeProvider.IsAssignable(typeof(Exception), activity.FaultType))
     {
         item = new ValidationError(SR.GetString("Error_TypeTypeMismatch", new object[] { "FaultType", typeof(Exception).FullName }), 0x51a) {
             PropertyName = "FaultType"
         };
         errors.Add(item);
     }
     if (activity.EnabledActivities.Count == 0)
     {
         errors.Add(new ValidationError(SR.GetString("Warning_EmptyBehaviourActivity", new object[] { typeof(FaultHandlerActivity).FullName, activity.QualifiedName }), 0x1a3, true));
     }
     if (activity.AlternateFlowActivities.Count > 0)
     {
         errors.Add(new ValidationError(SR.GetString("Error_ModelingConstructsCanNotContainModelingConstructs"), 0x61f));
     }
     return errors;
 }
Пример #15
0
        internal static ValidationError ValidateIdentifier(string propName, IServiceProvider context, string identifier)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            ValidationError error = null;
            if (identifier == null || identifier.Length == 0)
                error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, propName), ErrorNumbers.Error_PropertyNotSet);
            else
            {
                try
                {
                    ValidationHelpers.ValidateIdentifier(context, identifier);
                }
                catch (Exception e)
                {
                    error = new ValidationError(SR.GetString(SR.Error_InvalidIdentifier, propName, e.Message), ErrorNumbers.Error_InvalidIdentifier);
                }
            }
            if (error != null)
                error.PropertyName = propName;
            return error;
        }
 public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
 {
     ValidationErrorCollection errors = base.Validate(manager, obj);
     CompensateActivity compensate = obj as CompensateActivity;
     if (compensate == null)
     {
         throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(CompensateActivity).FullName }), "obj");
     }
     CompositeActivity parent = compensate.Parent;
     while (parent != null)
     {
         if (((parent is CompensationHandlerActivity) || (parent is FaultHandlerActivity)) || (parent is CancellationHandlerActivity))
         {
             break;
         }
         parent = parent.Parent;
     }
     if (parent == null)
     {
         errors.Add(new ValidationError(SR.GetString("Error_CompensateBadNesting"), 0x509));
     }
     ValidationError item = null;
     StringCollection compensatableTargets = CompensateActivity.GetCompensatableTargets(compensate);
     if (string.IsNullOrEmpty(compensate.TargetActivityName))
     {
         item = ValidationError.GetNotSetValidationError("TargetActivityName");
     }
     else if (!compensatableTargets.Contains(compensate.TargetActivityName))
     {
         item = new ValidationError(SR.GetString("Error_CompensateBadTargetTX", new object[] { "TargetActivityName", compensate.TargetActivityName, compensate.QualifiedName }), 0x563, false, "TargetActivityName");
     }
     if (item != null)
     {
         errors.Add(item);
     }
     return errors;
 }
Пример #17
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;
        }
Пример #18
0
        internal static ValidationError ValidateNameProperty(string propName, IServiceProvider context, string identifier)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            ValidationError error = null;
            if (identifier == null || identifier.Length == 0)
                error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, propName), ErrorNumbers.Error_PropertyNotSet);
            else
            {
                SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(context);
                CodeDomProvider provider = CompilerHelpers.GetCodeDomProvider(language);

                if (language == SupportedLanguages.CSharp && identifier.StartsWith("@", StringComparison.Ordinal) ||
                    language == SupportedLanguages.VB && identifier.StartsWith("[", StringComparison.Ordinal) && identifier.EndsWith("]", StringComparison.Ordinal) ||
                    !provider.IsValidIdentifier(provider.CreateEscapedIdentifier(identifier)))
                {
                    error = new ValidationError(SR.GetString(SR.Error_InvalidIdentifier, propName, SR.GetString(SR.Error_InvalidLanguageIdentifier, identifier)), ErrorNumbers.Error_InvalidIdentifier);
                }
            }
            if (error != null)
                error.PropertyName = propName;
            return error;
        }
 internal static ValidationError ValidateIdentifier(string propName, IServiceProvider context, string identifier)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     ValidationError error = null;
     if ((identifier == null) || (identifier.Length == 0))
     {
         error = new ValidationError(SR.GetString("Error_PropertyNotSet", new object[] { propName }), 0x116);
     }
     else
     {
         try
         {
             ValidateIdentifier(context, identifier);
         }
         catch (Exception exception)
         {
             error = new ValidationError(SR.GetString("Error_InvalidIdentifier", new object[] { propName, exception.Message }), 0x119);
         }
     }
     if (error != null)
     {
         error.PropertyName = propName;
     }
     return error;
 }
Пример #20
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;
        }
Пример #21
0
        internal static void InternalCompileFromDomBatch(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, string localAssemblyPath)
        {
            // Check all the library paths are valid.
            foreach (string libraryPath in parameters.LibraryPaths)
            {
                if (!XomlCompilerHelper.CheckPathName(libraryPath))
                {
                    WorkflowCompilerError libPathError =
                        new WorkflowCompilerError(string.Empty, 0, 0, ErrorNumbers.Error_LibraryPath.ToString(CultureInfo.InvariantCulture), string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.LibraryPathIsInvalid), libraryPath));
                    libPathError.IsWarning = true;
                    results.Errors.Add(libPathError);
                }
            }

            IList <AuthorizedType> authorizedTypes = null;

            if (parameters.CheckTypes)
            {
                //If we dont find the list of authorized types then return.
                authorizedTypes = WorkflowCompilationContext.Current.GetAuthorizedTypes();
                if (authorizedTypes == null)
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_ConfigFileMissingOrInvalid), ErrorNumbers.Error_ConfigFileMissingOrInvalid);
                    results.Errors.Add(CreateXomlCompilerError(error, parameters));
                    return;
                }
            }

            ITypeProvider typeProvider = WorkflowCompilationContext.Current.ServiceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;
            ArrayList     activities   = new ArrayList();

            using (PDBReader pdbReader = new PDBReader(localAssemblyPath))
            {
                // Validate all the compiled activities in the assembly.
                foreach (Type type in typeProvider.LocalAssembly.GetTypes())
                {
                    if (!TypeProvider.IsAssignable(typeof(Activity), type) || type.IsAbstract)
                    {
                        continue;
                    }

                    // Fetch file name.
                    string fileName = string.Empty;
                    WorkflowMarkupSourceAttribute[] sourceAttrs = (WorkflowMarkupSourceAttribute[])type.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false);
                    if (sourceAttrs != null && sourceAttrs.Length > 0)
                    {
                        fileName = sourceAttrs[0].FileName;
                    }
                    else
                    {
                        ConstructorInfo ctorMethod = type.GetConstructor(Type.EmptyTypes);
                        if (ctorMethod != null)
                        {
                            try
                            {
                                uint line = 0, column = 0;
                                pdbReader.GetSourceLocationForOffset((uint)ctorMethod.MetadataToken, 0, out fileName, out line, out column);
                            }
                            catch
                            {
                                // We don't want errors if the user has written their own custom
                                // activity and simply inherited the constructor
                            }
                        }

                        // In case of VB, if the ctor is autogenerated the PDB will not have symbol
                        // information. Use InitializeComponent method as the fallback.
                        if (String.IsNullOrEmpty(fileName))
                        {
                            MethodInfo initializeComponent = type.GetMethod("InitializeComponent", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
                            if (initializeComponent != null)
                            {
                                try
                                {
                                    uint line = 0, column = 0;
                                    pdbReader.GetSourceLocationForOffset((uint)initializeComponent.MetadataToken, 0, out fileName, out line, out column);

                                    if (!String.IsNullOrEmpty(fileName))
                                    {
                                        if (fileName.EndsWith(".designer.cs", StringComparison.OrdinalIgnoreCase))
                                        {
                                            fileName = fileName.Substring(0, fileName.Length - ".designer.cs".Length) + ".cs";
                                        }
                                        else if (fileName.EndsWith(".designer.vb", StringComparison.OrdinalIgnoreCase))
                                        {
                                            fileName = fileName.Substring(0, fileName.Length - ".designer.vb".Length) + ".vb";
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }

                    // Create the activity.
                    Activity activity = null;
                    try
                    {
                        try
                        {
                            Activity.ActivityType = type;
                            activity = Activator.CreateInstance(type) as Activity;
                        }
                        finally
                        {
                            Activity.ActivityType = null;
                        }
                        activity.UserData[UserDataKeys.CustomActivity] = false;
                        if (activity is CompositeActivity)
                        {
                            CompositeActivity compositeActivity = activity as CompositeActivity;
                            if (compositeActivity.CanModifyActivities)
                            {
                                results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_Missing_CanModifyProperties_False, activity.GetType().FullName), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                            }
                        }
                        if (sourceAttrs.Length > 0)
                        {
                            DesignerSerializationManager manager = new DesignerSerializationManager(WorkflowCompilationContext.Current.ServiceProvider);
                            Activity instance2 = null;
                            using (manager.CreateSession())
                            {
                                WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                                xomlSerializationManager.LocalAssembly = parameters.LocalAssembly;
                                using (XmlReader reader = XmlReader.Create((sourceAttrs[0].FileName)))
                                    instance2 = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, reader) as Activity;
                            }
                            if (instance2 is CompositeActivity)
                            {
                                ActivityMarkupSerializer.ReplaceChildActivities(activity as CompositeActivity, instance2 as CompositeActivity);
                            }
                        }
                    }
                    catch (TargetInvocationException tie)
                    {
                        // For TypeInitializationException, the message is available at the inner Exception
                        if (tie.InnerException is TypeInitializationException && tie.InnerException.InnerException != null)
                        {
                            results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_CustomActivityCantCreate, type.FullName, tie.InnerException.InnerException.ToString()), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        }
                        else if (tie.InnerException.InnerException != null)
                        {
                            results.Errors.Add(CreateXomlCompilerError(new ValidationError(tie.InnerException.InnerException.ToString(), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        }
                        else
                        {
                            results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_CustomActivityCantCreate, type.FullName, tie.InnerException.ToString()), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        }
                        continue;
                    }
                    catch (Exception e)
                    {
                        results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_CustomActivityCantCreate, type.FullName, e.ToString()), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        continue;
                    }

                    // Work around : another set of work arounds.
                    activity.SetValue(ActivityCodeDomSerializer.MarkupFileNameProperty, fileName);
                    activity.SetValue(WorkflowMarkupSerializer.XClassProperty, type.FullName);

                    // Run the validators.
                    ValidateActivity(activity, parameters, results);
                    activities.Add(activity);
                }
            }

            // Add all type load errors to compiler results.
            foreach (KeyValuePair <object, Exception> entry in typeProvider.TypeLoadErrors)
            {
                WorkflowCompilerError compilerError = new WorkflowCompilerError(string.Empty, 0, 0, ErrorNumbers.Error_TypeLoad.ToString(CultureInfo.InvariantCulture), entry.Value.Message);
                compilerError.IsWarning = true;
                results.Errors.Add(compilerError);
            }
            results.CompiledUnit = WorkflowCompilerInternal.GenerateCodeFromFileBatch(files, parameters, results);

            WorkflowCompilationContext context = WorkflowCompilationContext.Current;

            if (context == null)
            {
                throw new Exception(SR.GetString(SR.Error_MissingCompilationContext));
            }
            // Fix standard namespaces and root namespace.
            WorkflowMarkupSerializationHelpers.ReapplyRootNamespace(results.CompiledUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language));
            WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(results.CompiledUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language));
            if (!results.Errors.HasErrors)
            {
                // ask activities to generate code for themselves
                CodeGenerationManager codeGenerationManager = new CodeGenerationManager(WorkflowCompilationContext.Current.ServiceProvider);
                codeGenerationManager.Context.Push(results.CompiledUnit.Namespaces);
                foreach (Activity activity in activities)
                {
                    // Need to call code generators associated with the root activity.
                    if (activity.Parent == null)
                    {
                        foreach (System.Workflow.ComponentModel.Compiler.ActivityCodeGenerator codeGenerator in codeGenerationManager.GetCodeGenerators(activity.GetType()))
                        {
                            codeGenerator.GenerateCode(codeGenerationManager, activity);
                        }
                    }
                }

                // If only ccu needed then return.
                if (!parameters.GenerateCodeCompileUnitOnly || parameters.CheckTypes)
                {
                    // Convert all compile units to source files.
                    SupportedLanguages language        = CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse);
                    CodeDomProvider    codeDomProvider = CompilerHelpers.GetCodeDomProvider(language, parameters.CompilerVersion);
                    ArrayList          ccus            = new ArrayList((ICollection)parameters.UserCodeCompileUnits);
                    ccus.Add(results.CompiledUnit);

                    ArrayList sourceFilePaths = new ArrayList();
                    sourceFilePaths.AddRange(codeFiles);
                    sourceFilePaths.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, parameters, (CodeCompileUnit[])ccus.ToArray(typeof(CodeCompileUnit))));

                    // Finally give it to Code Compiler.
                    CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(parameters, (string[])sourceFilePaths.ToArray(typeof(string)));
                    results.AddCompilerErrorsFromCompilerResults(results2);
                    results.PathToAssembly            = results2.PathToAssembly;
                    results.NativeCompilerReturnValue = results2.NativeCompilerReturnValue;

                    if (!results.Errors.HasErrors && parameters.CheckTypes)
                    {
                        foreach (string referenceType in MetaDataReader.GetTypeRefNames(results2.CompiledAssembly.Location))
                        {
                            bool authorized = false;
                            foreach (AuthorizedType authorizedType in authorizedTypes)
                            {
                                if (authorizedType.RegularExpression.IsMatch(referenceType))
                                {
                                    authorized = (String.Compare(bool.TrueString, authorizedType.Authorized, StringComparison.OrdinalIgnoreCase) == 0);
                                    if (!authorized)
                                    {
                                        break;
                                    }
                                }
                            }
                            if (!authorized)
                            {
                                ValidationError error = new ValidationError(SR.GetString(SR.Error_TypeNotAuthorized, referenceType), ErrorNumbers.Error_TypeNotAuthorized);
                                results.Errors.Add(CreateXomlCompilerError(error, parameters));
                            }
                        }
                    }
                    //this line was throwing for the delay sign case. besides, copying PathToAssembly should do the same...
                    if (!results.Errors.HasErrors && !parameters.GenerateCodeCompileUnitOnly && parameters.GenerateInMemory &&
                        (string.IsNullOrEmpty(parameters.CompilerOptions) || !parameters.CompilerOptions.ToLower(CultureInfo.InvariantCulture).Contains("/delaysign")))
                    {
                        results.CompiledAssembly = results2.CompiledAssembly;
                    }
                }
            }
        }
Пример #22
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;
        }
Пример #23
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);
            }
        }
Пример #24
0
        [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]     // bogus since the casts are in different case statements
        internal static MethodInfo MapOperatorToMethod(
            CodeBinaryOperatorType op,
            Type lhs,
            CodeExpression lhsExpression,
            Type rhs,
            CodeExpression rhsExpression,
            RuleValidation validator,
            out ValidationError error)
        {
            // determine what the method name should be
            string methodName;
            string message;
            OperatorGrouping group;

            switch (op)
            {
                case CodeBinaryOperatorType.ValueEquality:
                    methodName = "op_Equality";
                    group = OperatorGrouping.Equality;
                    break;
                case CodeBinaryOperatorType.GreaterThan:
                    methodName = "op_GreaterThan";
                    group = OperatorGrouping.Relational;
                    break;
                case CodeBinaryOperatorType.GreaterThanOrEqual:
                    methodName = "op_GreaterThanOrEqual";
                    group = OperatorGrouping.Relational;
                    break;
                case CodeBinaryOperatorType.LessThan:
                    methodName = "op_LessThan";
                    group = OperatorGrouping.Relational;
                    break;
                case CodeBinaryOperatorType.LessThanOrEqual:
                    methodName = "op_LessThanOrEqual";
                    group = OperatorGrouping.Relational;
                    break;
                case CodeBinaryOperatorType.Add:
                    methodName = "op_Addition";
                    group = OperatorGrouping.Arithmetic;
                    break;
                case CodeBinaryOperatorType.Subtract:
                    methodName = "op_Subtraction";
                    group = OperatorGrouping.Arithmetic;
                    break;
                case CodeBinaryOperatorType.Multiply:
                    methodName = "op_Multiply";
                    group = OperatorGrouping.Arithmetic;
                    break;
                case CodeBinaryOperatorType.Divide:
                    methodName = "op_Division";
                    group = OperatorGrouping.Arithmetic;
                    break;
                case CodeBinaryOperatorType.Modulus:
                    methodName = "op_Modulus";
                    group = OperatorGrouping.Arithmetic;
                    break;
                case CodeBinaryOperatorType.BitwiseAnd:
                    methodName = "op_BitwiseAnd";
                    group = OperatorGrouping.Arithmetic;
                    break;
                case CodeBinaryOperatorType.BitwiseOr:
                    methodName = "op_BitwiseOr";
                    group = OperatorGrouping.Arithmetic;
                    break;
                default:
                    Debug.Assert(false, "Operator " + op.ToString() + " not implemented");
                    message = string.Format(CultureInfo.CurrentCulture, Messages.BinaryOpNotSupported, op.ToString());
                    error = new ValidationError(message, ErrorNumbers.Error_CodeExpressionNotHandled);
                    return null;
            }

            // NOTE: types maybe NullLiteral, which signifies the constant "null"
            List<MethodInfo> candidates = new List<MethodInfo>();
            bool lhsNullable = ConditionHelper.IsNullableValueType(lhs);
            bool rhsNullable = ConditionHelper.IsNullableValueType(rhs);
            Type lhsType0 = (lhsNullable) ? Nullable.GetUnderlyingType(lhs) : lhs;
            Type rhsType0 = (rhsNullable) ? Nullable.GetUnderlyingType(rhs) : rhs;

            // special cases for enums
            if (lhsType0.IsEnum)
            {
                // only 3 cases (U = underlying type of E):
                //    E = E + U
                //    U = E - E
                //    E = E - U
                // plus the standard comparisons (E == E, E > E, etc.)
                // need to also allow E == 0
                Type underlyingType;
                switch (op)
                {
                    case CodeBinaryOperatorType.Add:
                        underlyingType = EnumHelper.GetUnderlyingType(lhsType0);
                        if ((underlyingType != null) &&
                            (RuleValidation.TypesAreAssignable(rhsType0, underlyingType, rhsExpression, out error)))
                        {
                            error = null;
                            return new EnumOperationMethodInfo(lhs, op, rhs, false);
                        }
                        break;
                    case CodeBinaryOperatorType.Subtract:
                        underlyingType = EnumHelper.GetUnderlyingType(lhsType0);
                        if (underlyingType != null)
                        {
                            if (lhsType0 == rhsType0)
                            {
                                // E - E
                                error = null;
                                return new EnumOperationMethodInfo(lhs, op, rhs, false);
                            }
                            else if (DecimalIntegerLiteralZero(rhs, rhsExpression as CodePrimitiveExpression))
                            {
                                // E - 0, can convert 0 to E
                                error = null;
                                return new EnumOperationMethodInfo(lhs, op, rhs, true);
                            }
                            else if (RuleValidation.TypesAreAssignable(rhsType0, underlyingType, rhsExpression, out error))
                            {
                                // expression not passed to TypesAreAssignable, so not looking for constants (since 0 is all we care about)
                                error = null;
                                return new EnumOperationMethodInfo(lhs, op, rhs, false);
                            }
                        }
                        break;
                    case CodeBinaryOperatorType.ValueEquality:
                    case CodeBinaryOperatorType.LessThan:
                    case CodeBinaryOperatorType.LessThanOrEqual:
                    case CodeBinaryOperatorType.GreaterThan:
                    case CodeBinaryOperatorType.GreaterThanOrEqual:
                        if (lhsType0 == rhsType0)
                        {
                            error = null;
                            return new EnumOperationMethodInfo(lhs, op, rhs, false);
                        }
                        else if (lhsNullable && (rhs == typeof(NullLiteral)))
                        {
                            // handle enum? op null
                            // treat the rhs as the same nullable enum
                            error = null;
                            return new EnumOperationMethodInfo(lhs, op, lhs, false);
                        }
                        else if (DecimalIntegerLiteralZero(rhs, rhsExpression as CodePrimitiveExpression))
                        {
                            error = null;
                            return new EnumOperationMethodInfo(lhs, op, rhs, true);
                        }
                        break;
                }
                // can't do it, sorry
                // but check if there is a user-defined operator that works
            }
            else if (rhsType0.IsEnum)
            {
                // lhs != enum, so only 2 cases (U = underlying type of E):
                //    E = U + E
                //    E = U - E
                // comparisons are E == E, etc., so if the lhs is not an enum, too bad
                // although we need to check for 0 == E
                Type underlyingType;
                switch (op)
                {
                    case CodeBinaryOperatorType.Add:
                        underlyingType = EnumHelper.GetUnderlyingType(rhsType0);
                        if ((underlyingType != null) &&
                            (RuleValidation.TypesAreAssignable(lhsType0, underlyingType, lhsExpression, out error)))
                        {
                            error = null;
                            return new EnumOperationMethodInfo(lhs, op, rhs, false);
                        }
                        break;

                    case CodeBinaryOperatorType.Subtract:
                        underlyingType = EnumHelper.GetUnderlyingType(rhsType0);
                        if (underlyingType != null)
                        {
                            CodePrimitiveExpression primitive = lhsExpression as CodePrimitiveExpression;
                            if (DecimalIntegerLiteralZero(lhs, primitive))
                            {
                                // 0 - E, can convert 0 to E
                                error = null;
                                return new EnumOperationMethodInfo(lhs, op, rhs, true);
                            }
                            else if (RuleValidation.TypesAreAssignable(lhsType0, underlyingType, lhsExpression, out error))
                            {
                                // expression not passed to TypesAreAssignable, so not looking for constants (since 0 is all we care about)
                                error = null;
                                return new EnumOperationMethodInfo(lhs, op, rhs, false);
                            }
                        }
                        break;

                    case CodeBinaryOperatorType.ValueEquality:
                    case CodeBinaryOperatorType.LessThan:
                    case CodeBinaryOperatorType.LessThanOrEqual:
                    case CodeBinaryOperatorType.GreaterThan:
                    case CodeBinaryOperatorType.GreaterThanOrEqual:
                        if (rhsNullable && (lhs == typeof(NullLiteral)))
                        {
                            // handle null op enum?
                            // treat the lhs as the same nullable enum type
                            error = null;
                            return new EnumOperationMethodInfo(rhs, op, rhs, false);
                        }
                        else if (DecimalIntegerLiteralZero(lhs, lhsExpression as CodePrimitiveExpression))
                        {
                            error = null;
                            return new EnumOperationMethodInfo(lhs, op, rhs, true);
                        }
                        break;
                }

                // can't do it, sorry
                // but check if there is a user-defined operator that works
            }

            // enum specific operations already handled, see if one side (or both) define operators
            AddOperatorOverloads(lhsType0, methodName, lhs, rhs, candidates);
            AddOperatorOverloads(rhsType0, methodName, lhs, rhs, candidates);
            if (lhsNullable || rhsNullable || (lhs == typeof(NullLiteral)) || (rhs == typeof(NullLiteral)))
            {
                // need to add in lifted methods
                AddLiftedOperators(lhsType0, methodName, group, lhsType0, rhsType0, candidates);
                AddLiftedOperators(rhsType0, methodName, group, lhsType0, rhsType0, candidates);
            }

            if (candidates.Count == 0)
            {
                // no overrides, so get the default list
                methodName = methodName.Substring(3);       // strip off the op_
                foreach (MethodInfo mi in typeof(DefaultOperators).GetMethods())
                {
                    if (mi.Name == methodName)
                    {
                        ParameterInfo[] parameters = mi.GetParameters();
                        Type parm1 = parameters[0].ParameterType;
                        Type parm2 = parameters[1].ParameterType;
                        if (RuleValidation.ImplicitConversion(lhs, parm1) &&
                            RuleValidation.ImplicitConversion(rhs, parm2))
                        {
                            candidates.Add(mi);
                        }
                    }
                }

                // if no candidates and ==, can we use object == object?
                if ((candidates.Count == 0) && ("Equality" == methodName))
                {
                    // C# 7.9.6
                    // references must be compatible
                    // no boxing
                    // value types can't be compared
                    if ((!lhs.IsValueType) && (!rhs.IsValueType))
                    {
                        // they are not classes, so references need to be compatible
                        // also check for null (which is NullLiteral type) -- null is compatible with any object type
                        if ((lhs == typeof(NullLiteral)) || (rhs == typeof(NullLiteral)) ||
                            (lhs.IsAssignableFrom(rhs)) || (rhs.IsAssignableFrom(lhs)))
                        {
                            candidates.Add(ObjectEquality);
                        }
                    }
                }

                // if no candidates and nullable, add lifted operators
                if ((candidates.Count == 0) && ((lhsNullable || rhsNullable || (lhs == typeof(NullLiteral)) || (rhs == typeof(NullLiteral)))))
                {
                    foreach (MethodInfo mi in typeof(DefaultOperators).GetMethods())
                    {
                        if (mi.Name == methodName)
                        {
                            ParameterInfo[] parameters = mi.GetParameters();
                            MethodInfo liftedMethod = EvaluateLiftedMethod(mi, parameters, group, lhsType0, rhsType0);
                            if (liftedMethod != null)
                                candidates.Add(liftedMethod);
                        }
                    }
                }
            }
            if (candidates.Count == 1)
            {
                // only 1, so it is it
                error = null;
                return candidates[0];
            }
            else if (candidates.Count == 0)
            {
                // nothing matched
                message = string.Format(CultureInfo.CurrentCulture,
                    (group == OperatorGrouping.Arithmetic) ? Messages.ArithOpBadTypes : Messages.RelationalOpBadTypes,
                    op.ToString(),
                    (lhs == typeof(NullLiteral)) ? Messages.NullValue : RuleDecompiler.DecompileType(lhs),
                    (rhs == typeof(NullLiteral)) ? Messages.NullValue : RuleDecompiler.DecompileType(rhs));
                error = new ValidationError(message, ErrorNumbers.Error_OperandTypesIncompatible);
                return null;
            }
            else
            {
                // more than 1, so pick the best one
                MethodInfo bestFit = validator.FindBestCandidate(null, candidates, lhs, rhs);
                if (bestFit != null)
                {
                    error = null;
                    return bestFit;
                }
                // must be ambiguous. Since there are at least 2 choices, show only the first 2
                message = string.Format(CultureInfo.CurrentCulture,
                    Messages.AmbiguousOperator,
                    op.ToString(),
                    RuleDecompiler.DecompileMethod(candidates[0]),
                    RuleDecompiler.DecompileMethod(candidates[1]));
                error = new ValidationError(message, ErrorNumbers.Error_OperandTypesIncompatible);
                return null;
            }
        }
Пример #25
0
        internal static RuleBinaryExpressionInfo AllowedComparison(
            Type lhs,
            CodeExpression lhsExpression,
            Type rhs,
            CodeExpression rhsExpression,
            CodeBinaryOperatorType comparison,
            RuleValidation validator,
            out ValidationError error)
        {
            // note that null values come in as a NullLiteral type
            TypeFlags lhsFlags, rhsFlags;

            // are the types supported?
            if ((supportedTypes.TryGetValue(lhs, out lhsFlags)) && (supportedTypes.TryGetValue(rhs, out rhsFlags)))
            {
                // both sides supported
                if (lhsFlags == rhsFlags)
                {
                    // both sides the same type, so it's allowed
                    // only allow equality on booleans
                    if ((lhsFlags == TypeFlags.Bool) && (comparison != CodeBinaryOperatorType.ValueEquality))
                    {
                        string message = string.Format(CultureInfo.CurrentCulture, Messages.RelationalOpBadTypes, comparison.ToString(),
                            RuleDecompiler.DecompileType(lhs),
                            RuleDecompiler.DecompileType(rhs));
                        error = new ValidationError(message, ErrorNumbers.Error_OperandTypesIncompatible);
                        return null;
                    }
                    error = null;
                    return new RuleBinaryExpressionInfo(lhs, rhs, typeof(bool));
                }

                // if not the same, only certain combinations allowed
                switch (lhsFlags | rhsFlags)
                {
                    case TypeFlags.Decimal | TypeFlags.SignedNumbers:
                    case TypeFlags.Decimal | TypeFlags.UnsignedNumbers:
                    case TypeFlags.Decimal | TypeFlags.ULong:
                    case TypeFlags.Float | TypeFlags.SignedNumbers:
                    case TypeFlags.Float | TypeFlags.UnsignedNumbers:
                    case TypeFlags.Float | TypeFlags.ULong:
                    case TypeFlags.ULong | TypeFlags.UnsignedNumbers:
                    case TypeFlags.SignedNumbers | TypeFlags.UnsignedNumbers:
                        error = null;
                        return new RuleBinaryExpressionInfo(lhs, rhs, typeof(bool));
                }
                string message2 = string.Format(CultureInfo.CurrentCulture, Messages.RelationalOpBadTypes, comparison.ToString(),
                    (lhs == typeof(NullLiteral)) ? Messages.NullValue : RuleDecompiler.DecompileType(lhs),
                    (rhs == typeof(NullLiteral)) ? Messages.NullValue : RuleDecompiler.DecompileType(rhs));
                error = new ValidationError(message2, ErrorNumbers.Error_OperandTypesIncompatible);
                return null;
            }
            else
            {
                // see if they override the operator
                MethodInfo operatorOverride = MapOperatorToMethod(comparison, lhs, lhsExpression, rhs, rhsExpression, validator, out error);
                if (operatorOverride != null)
                    return new RuleBinaryExpressionInfo(lhs, rhs, operatorOverride);

                // unable to evaluate, so return false
                return null;
            }
        }
 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);
 }
Пример #27
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection errors = base.Validate(manager, obj);
            Activity activity = obj as Activity;

            if (activity == null)
            {
                throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(Activity).FullName }), "obj");
            }
            WorkflowTransactionOptions transactionOptions = TransactedContextFilter.GetTransactionOptions(activity);

            if (transactionOptions != null)
            {
                if (FaultAndCancellationHandlingFilter.GetFaultHandlers(activity) != null)
                {
                    ValidationError item = new ValidationError(SR.GetString("Error_AtomicScopeWithFaultHandlersActivityDecl", new object[] { activity.Name }), 0x52c);
                    errors.Add(item);
                }
                if (FaultAndCancellationHandlingFilter.GetCancellationHandler(activity) != null)
                {
                    ValidationError error2 = new ValidationError(SR.GetString("Error_AtomicScopeWithCancellationHandlerActivity", new object[] { activity.Name }), 0x575);
                    errors.Add(error2);
                }
                for (Activity activity4 = activity.Parent; activity4 != null; activity4 = activity4.Parent)
                {
                    if (activity4.SupportsTransaction)
                    {
                        errors.Add(new ValidationError(SR.GetString("Error_AtomicScopeNestedInNonLRT"), 0x52e));
                        break;
                    }
                }
                Queue <Activity> queue = new Queue <Activity>(Helpers.GetAllEnabledActivities((CompositeActivity)activity));
                while (queue.Count > 0)
                {
                    Activity activity5 = queue.Dequeue();
                    if (activity5.PersistOnClose)
                    {
                        errors.Add(new ValidationError(SR.GetString("Error_LRTScopeNestedInNonLRT"), 0x52f));
                        break;
                    }
                    if (activity5 is ICompensatableActivity)
                    {
                        errors.Add(new ValidationError(SR.GetString("Error_NestedCompensatableActivity", new object[] { activity5.QualifiedName }), 0x1a6));
                        break;
                    }
                    if (activity5 is CompositeActivity)
                    {
                        foreach (Activity activity6 in Helpers.GetAllEnabledActivities((CompositeActivity)activity5))
                        {
                            queue.Enqueue(activity6);
                        }
                    }
                }
                if (transactionOptions.TimeoutDuration.Ticks < 0L)
                {
                    ValidationError error3 = new ValidationError(SR.GetString("Error_NegativeValue", new object[] { transactionOptions.TimeoutDuration.ToString(), "TimeoutDuration" }), 0x531)
                    {
                        PropertyName = "TimeoutDuration"
                    };
                    errors.Add(error3);
                }
            }
            return(errors);
        }
        private ValidationErrorCollection ValidateDependencyProperty(DependencyObject dependencyObject, DependencyProperty dependencyProperty, ValidationManager manager)
        {
            ValidationErrorCollection errors = new ValidationErrorCollection();

            Attribute[]      attributes    = dependencyProperty.DefaultMetadata.GetAttributes(typeof(ValidationOptionAttribute));
            ValidationOption option        = (attributes.Length > 0) ? ((ValidationOptionAttribute)attributes[0]).ValidationOption : ValidationOption.Optional;
            Activity         propertyOwner = manager.Context[typeof(Activity)] as Activity;

            if (propertyOwner == null)
            {
                throw new InvalidOperationException(SR.GetString("Error_ContextStackItemMissing", new object[] { typeof(Activity).FullName }));
            }
            PropertyValidationContext context = new PropertyValidationContext(propertyOwner, dependencyProperty);

            manager.Context.Push(context);
            try
            {
                if (dependencyProperty.DefaultMetadata.DefaultValue != null)
                {
                    if (!dependencyProperty.PropertyType.IsValueType && (dependencyProperty.PropertyType != typeof(string)))
                    {
                        errors.Add(new ValidationError(SR.GetString("Error_PropertyDefaultIsReference", new object[] { dependencyProperty.Name }), 0x1a8));
                    }
                    else if (!dependencyProperty.PropertyType.IsAssignableFrom(dependencyProperty.DefaultMetadata.DefaultValue.GetType()))
                    {
                        errors.Add(new ValidationError(SR.GetString("Error_PropertyDefaultTypeMismatch", new object[] { dependencyProperty.Name, dependencyProperty.PropertyType.FullName, dependencyProperty.DefaultMetadata.DefaultValue.GetType().FullName }), 0x1a9));
                    }
                }
                object propValue = null;
                if (dependencyObject.IsBindingSet(dependencyProperty))
                {
                    propValue = dependencyObject.GetBinding(dependencyProperty);
                }
                else if (!dependencyProperty.IsEvent)
                {
                    propValue = dependencyObject.GetValue(dependencyProperty);
                }
                if ((propValue == null) || (propValue == dependencyProperty.DefaultMetadata.DefaultValue))
                {
                    if (dependencyProperty.IsEvent)
                    {
                        propValue = dependencyObject.GetHandler(dependencyProperty);
                        if (propValue == null)
                        {
                            propValue = WorkflowMarkupSerializationHelpers.GetEventHandlerName(dependencyObject, dependencyProperty.Name);
                        }
                        if ((propValue is string) && !string.IsNullOrEmpty((string)propValue))
                        {
                            errors.AddRange(this.ValidateEvent(propertyOwner, dependencyProperty, propValue, manager));
                        }
                    }
                    else
                    {
                        propValue = dependencyObject.GetValue(dependencyProperty);
                    }
                }
                bool flag = (propertyOwner.Parent != null) || ((propertyOwner is CompositeActivity) && (((CompositeActivity)propertyOwner).EnabledActivities.Count != 0));
                if (((option == ValidationOption.Required) && ((propValue == null) || ((propValue is string) && string.IsNullOrEmpty((string)propValue)))) && (dependencyProperty.DefaultMetadata.IsMetaProperty && flag))
                {
                    errors.Add(ValidationError.GetNotSetValidationError(base.GetFullPropertyName(manager)));
                    return(errors);
                }
                if (propValue == null)
                {
                    return(errors);
                }
                if (propValue is IList)
                {
                    PropertyValidationContext context2 = new PropertyValidationContext(propValue, null, string.Empty);
                    manager.Context.Push(context2);
                    try
                    {
                        foreach (object obj3 in (IList)propValue)
                        {
                            errors.AddRange(ValidationHelpers.ValidateObject(manager, obj3));
                        }
                        return(errors);
                    }
                    finally
                    {
                        manager.Context.Pop();
                    }
                }
                if (dependencyProperty.ValidatorType != null)
                {
                    Validator validator = null;
                    try
                    {
                        validator = Activator.CreateInstance(dependencyProperty.ValidatorType) as Validator;
                        if (validator == null)
                        {
                            errors.Add(new ValidationError(SR.GetString("Error_CreateValidator", new object[] { dependencyProperty.ValidatorType.FullName }), 0x106));
                            return(errors);
                        }
                        errors.AddRange(validator.Validate(manager, propValue));
                        return(errors);
                    }
                    catch
                    {
                        errors.Add(new ValidationError(SR.GetString("Error_CreateValidator", new object[] { dependencyProperty.ValidatorType.FullName }), 0x106));
                        return(errors);
                    }
                }
                errors.AddRange(ValidationHelpers.ValidateObject(manager, propValue));
            }
            finally
            {
                manager.Context.Pop();
            }
            return(errors);
        }
Пример #29
0
        private ValidationErrorCollection ValidateMethod(ValidationManager manager, Activity activity, MethodBind bind, BindValidationContext validationBindContext)
        {
            ValidationErrorCollection errors = new ValidationErrorCollection();

            if ((validationBindContext.Access & AccessTypes.Write) != 0)
            {
                ValidationError item = new ValidationError(SR.GetString("Error_HandlerReadOnly"), 0x133)
                {
                    PropertyName = base.GetFullPropertyName(manager)
                };
                errors.Add(item);
                return(errors);
            }
            if (!TypeProvider.IsAssignable(typeof(Delegate), validationBindContext.TargetType))
            {
                ValidationError error2 = new ValidationError(SR.GetString("Error_TypeNotDelegate", new object[] { validationBindContext.TargetType.FullName }), 0x134)
                {
                    PropertyName = base.GetFullPropertyName(manager)
                };
                errors.Add(error2);
                return(errors);
            }
            string   name = bind.Name;
            Activity enclosingActivity = Helpers.GetEnclosingActivity(activity);

            if ((name.IndexOf('.') != -1) && (enclosingActivity != null))
            {
                enclosingActivity = Helpers.GetDataSourceActivity(activity, bind.Name, out name);
            }
            if (enclosingActivity == null)
            {
                ValidationError error3 = new ValidationError(SR.GetString("Error_NoEnclosingContext", new object[] { activity.Name }), 0x130)
                {
                    PropertyName = base.GetFullPropertyName(manager) + ".Name"
                };
                errors.Add(error3);
                return(errors);
            }
            string errorText       = string.Empty;
            int    errorNumber     = -1;
            Type   dataSourceClass = Helpers.GetDataSourceClass(enclosingActivity, manager);

            if (dataSourceClass == null)
            {
                errorText   = SR.GetString("Error_TypeNotResolvedInMethodName", new object[] { base.GetFullPropertyName(manager) + ".Name" });
                errorNumber = 0x135;
            }
            else
            {
                try
                {
                    ValidationHelpers.ValidateIdentifier(manager, name);
                }
                catch (Exception exception)
                {
                    errors.Add(new ValidationError(exception.Message, 0x119));
                }
                MethodInfo method = validationBindContext.TargetType.GetMethod("Invoke");
                if (method == null)
                {
                    throw new Exception(SR.GetString("Error_DelegateNoInvoke", new object[] { validationBindContext.TargetType.FullName }));
                }
                List <Type> list = new List <Type>();
                foreach (ParameterInfo info2 in method.GetParameters())
                {
                    list.Add(info2.ParameterType);
                }
                MethodInfo info3 = Helpers.GetMethodExactMatch(dataSourceClass, name, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, list.ToArray(), null);
                if (info3 == null)
                {
                    if (dataSourceClass.GetMethod(name, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance) != null)
                    {
                        errorText   = SR.GetString("Error_MethodSignatureMismatch", new object[] { base.GetFullPropertyName(manager) + ".Name" });
                        errorNumber = 310;
                    }
                    else
                    {
                        errorText   = SR.GetString("Error_MethodNotExists", new object[] { base.GetFullPropertyName(manager) + ".Name", bind.Name });
                        errorNumber = 0x137;
                    }
                }
                else if (!method.ReturnType.Equals(info3.ReturnType))
                {
                    errorText   = SR.GetString("Error_MethodReturnTypeMismatch", new object[] { base.GetFullPropertyName(manager), method.ReturnType.FullName });
                    errorNumber = 0x139;
                }
            }
            if (errorText.Length > 0)
            {
                ValidationError error4 = new ValidationError(errorText, errorNumber)
                {
                    PropertyName = base.GetFullPropertyName(manager) + ".Path"
                };
                errors.Add(error4);
            }
            return(errors);
        }
Пример #30
0
        internal static CodeCompileUnit GenerateCodeFromFileBatch(string[] files, WorkflowCompilerParameters parameters, WorkflowCompilerResults results)
        {
            WorkflowCompilationContext context = WorkflowCompilationContext.Current;

            if (context == null)
            {
                throw new Exception(SR.GetString(SR.Error_MissingCompilationContext));
            }

            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            foreach (string fileName in files)
            {
                Activity rootActivity = null;
                try
                {
                    DesignerSerializationManager manager = new DesignerSerializationManager(context.ServiceProvider);
                    using (manager.CreateSession())
                    {
                        WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                        xomlSerializationManager.WorkflowMarkupStack.Push(parameters);
                        xomlSerializationManager.LocalAssembly = parameters.LocalAssembly;
                        using (XmlReader reader = XmlReader.Create(fileName))
                            rootActivity = WorkflowMarkupSerializationHelpers.LoadXomlDocument(xomlSerializationManager, reader, fileName);

                        if (parameters.LocalAssembly != null)
                        {
                            foreach (object error in manager.Errors)
                            {
                                if (error is WorkflowMarkupSerializationException)
                                {
                                    results.Errors.Add(new WorkflowCompilerError(fileName, (WorkflowMarkupSerializationException)error));
                                }
                                else
                                {
                                    results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), error.ToString()));
                                }
                            }
                        }
                    }
                }
                catch (WorkflowMarkupSerializationException xomlSerializationException)
                {
                    results.Errors.Add(new WorkflowCompilerError(fileName, xomlSerializationException));
                    continue;
                }
                catch (Exception e)
                {
                    results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message)));
                    continue;
                }

                if (rootActivity == null)
                {
                    results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_RootActivityTypeInvalid)));
                    continue;
                }

                bool createNewClass = (!string.IsNullOrEmpty(rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string));
                if (!createNewClass)
                {
                    results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CannotCompile_No_XClass)));
                    continue;
                }

                //NOTE: CompileWithNoCode is meaningless now. It means no x:Code in a XOML file. It exists until the FP migration is done
                //Ideally FP should just use XOML files w/o X:Class and run them w/o ever compiling them
                if ((parameters.CompileWithNoCode) && XomlCompilerHelper.HasCodeWithin(rootActivity))
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_CodeWithinNotAllowed), ErrorNumbers.Error_CodeWithinNotAllowed);
                    error.UserData[typeof(Activity)] = rootActivity;
                    results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters));
                }

                ValidationErrorCollection errors = new ValidationErrorCollection();

                errors = ValidateIdentifiers(context.ServiceProvider, rootActivity);
                foreach (ValidationError error in errors)
                {
                    results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters));
                }

                if (results.Errors.HasErrors)
                {
                    continue;
                }

                codeCompileUnit.Namespaces.AddRange(WorkflowMarkupSerializationHelpers.GenerateCodeFromXomlDocument(rootActivity, fileName, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language), context.ServiceProvider));
            }

            WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(codeCompileUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language));
            return(codeCompileUnit);
        }
 internal static ValidationError ValidateNameProperty(string propName, IServiceProvider context, string identifier)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     ValidationError error = null;
     if ((identifier == null) || (identifier.Length == 0))
     {
         error = new ValidationError(SR.GetString("Error_PropertyNotSet", new object[] { propName }), 0x116);
     }
     else
     {
         System.Workflow.Activities.Common.SupportedLanguages supportedLanguage = System.Workflow.Activities.Common.CompilerHelpers.GetSupportedLanguage(context);
         CodeDomProvider codeDomProvider = System.Workflow.Activities.Common.CompilerHelpers.GetCodeDomProvider(supportedLanguage);
         if ((((supportedLanguage == System.Workflow.Activities.Common.SupportedLanguages.CSharp) && identifier.StartsWith("@", StringComparison.Ordinal)) || (((supportedLanguage == System.Workflow.Activities.Common.SupportedLanguages.VB) && identifier.StartsWith("[", StringComparison.Ordinal)) && identifier.EndsWith("]", StringComparison.Ordinal))) || !codeDomProvider.IsValidIdentifier(codeDomProvider.CreateEscapedIdentifier(identifier)))
         {
             error = new ValidationError(SR.GetString("Error_InvalidIdentifier", new object[] { propName, SR.GetString("Error_InvalidLanguageIdentifier", new object[] { identifier }) }), 0x119);
         }
     }
     if (error != null)
     {
         error.PropertyName = propName;
     }
     return error;
 }
 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);
 }
Пример #33
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            InvokeWorkflowActivity invokeWorkflow = obj as InvokeWorkflowActivity;
            if (invokeWorkflow == null)
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(InvokeWorkflowActivity).FullName), "obj");

            if (invokeWorkflow.TargetWorkflow == null)
            {
                ValidationError error = new ValidationError(SR.GetString(SR.Error_TypePropertyInvalid, "TargetWorkflow"), ErrorNumbers.Error_PropertyNotSet);
                error.PropertyName = "TargetWorkflow";
                validationErrors.Add(error);
            }
            else
            {
                ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider));
                if (typeProvider == null)
                    throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));

                Type targetWorkflowType = invokeWorkflow.TargetWorkflow;
                if (targetWorkflowType.Assembly == null && typeProvider.LocalAssembly != null)
                {
                    Type workflowType = typeProvider.LocalAssembly.GetType(targetWorkflowType.FullName);
                    if (workflowType != null)
                        targetWorkflowType = workflowType;
                }

                if (!TypeProvider.IsAssignable(typeof(Activity), targetWorkflowType))
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_TypeIsNotRootActivity, "TargetWorkflow"), ErrorNumbers.Error_TypeIsNotRootActivity);
                    error.PropertyName = "TargetWorkflow";
                    validationErrors.Add(error);
                }
                else
                {
                    Activity rootActivity = null;
                    try
                    {
                        rootActivity = Activator.CreateInstance(targetWorkflowType) as Activity;
                    }
                    catch (Exception)
                    {
                        //
                    }

                    if (rootActivity == null)
                    {
                        ValidationError error = new ValidationError(SR.GetString(SR.Error_GetCalleeWorkflow, invokeWorkflow.TargetWorkflow), ErrorNumbers.Error_GetCalleeWorkflow);
                        error.PropertyName = "TargetWorkflow";
                        validationErrors.Add(error);
                    }
                    else
                    {
                        // Exec can't have activate receive.
                        Walker walker = new Walker();
                        walker.FoundActivity += delegate(Walker w, WalkerEventArgs args)
                        {
                            if ((args.CurrentActivity is WebServiceInputActivity && ((WebServiceInputActivity)args.CurrentActivity).IsActivating))
                            {
                                ValidationError validationError = new ValidationError(SR.GetString(SR.Error_ExecWithActivationReceive), ErrorNumbers.Error_ExecWithActivationReceive);
                                validationError.PropertyName = "Name";
                                validationErrors.Add(validationError);

                                args.Action = WalkerAction.Abort;
                            }
                        };

                        walker.Walk((Activity)rootActivity);

                        bool inAtomicScope = false;
                        Activity parentScope = invokeWorkflow.Parent;
                        while (parentScope != null)
                        {
                            if (parentScope is CompensatableTransactionScopeActivity || parentScope is TransactionScopeActivity)
                            {
                                inAtomicScope = true;
                                break;
                            }
                            parentScope = parentScope.Parent;
                        }

                        // Validate that if the workflow is transactional or being exec'd then it is not enclosed in an atomic scope.
                        if (inAtomicScope)
                        {
                            ValidationError validationError = new ValidationError(SR.GetString(SR.Error_ExecInAtomicScope), ErrorNumbers.Error_ExecInAtomicScope);
                            validationErrors.Add(validationError);
                        }

                        foreach (WorkflowParameterBinding paramBinding in invokeWorkflow.ParameterBindings)
                        {
                            PropertyInfo propertyInfo = null;

                            propertyInfo = targetWorkflowType.GetProperty(paramBinding.ParameterName);
                            if (propertyInfo == null)
                            {
                                ValidationError validationError = new ValidationError(SR.GetString(SR.Error_ParameterNotFound, paramBinding.ParameterName), ErrorNumbers.Error_ParameterNotFound);
                                if (InvokeWorkflowActivity.ReservedParameterNames.Contains(paramBinding.ParameterName))
                                    validationError.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(invokeWorkflow.GetType(), paramBinding.ParameterName);

                                validationErrors.Add(validationError);
                                continue;
                            }

                            Type parameterType = propertyInfo.PropertyType;
                            if (paramBinding.GetBinding(WorkflowParameterBinding.ValueProperty) != null)
                            {
                                ValidationErrorCollection memberErrors = ValidationHelpers.ValidateProperty(manager, invokeWorkflow, paramBinding.GetBinding(WorkflowParameterBinding.ValueProperty), new PropertyValidationContext(paramBinding, null, paramBinding.ParameterName), new BindValidationContext(parameterType, AccessTypes.Read));

                                if (memberErrors.Count != 0)
                                {
                                    validationErrors.AddRange(memberErrors);
                                    continue;
                                }
                            }
                        }
                    }
                }
            }

            return validationErrors;
        }
Пример #34
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection errors = base.Validate(manager, obj);
            ActivityBind bind = obj as ActivityBind;

            if (bind == null)
            {
                throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(ActivityBind).FullName }), "obj");
            }
            Activity activity = manager.Context[typeof(Activity)] as Activity;

            if (activity == null)
            {
                throw new InvalidOperationException(SR.GetString("Error_ContextStackItemMissing", new object[] { typeof(Activity).Name }));
            }
            PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext;

            if (validationContext == null)
            {
                throw new InvalidOperationException(SR.GetString("Error_ContextStackItemMissing", new object[] { typeof(BindValidationContext).Name }));
            }
            ValidationError item = null;

            if (string.IsNullOrEmpty(bind.Name))
            {
                item = new ValidationError(SR.GetString("Error_IDNotSetForActivitySource"), 0x613)
                {
                    PropertyName = base.GetFullPropertyName(manager) + ".Name"
                };
                errors.Add(item);
                return(errors);
            }
            Activity refActivity = Helpers.ParseActivityForBind(activity, bind.Name);

            if (refActivity == null)
            {
                if (bind.Name.StartsWith("/"))
                {
                    item = new ValidationError(SR.GetString("Error_CannotResolveRelativeActivity", new object[] { bind.Name }), 0x128);
                }
                else
                {
                    item = new ValidationError(SR.GetString("Error_CannotResolveActivity", new object[] { bind.Name }), 0x129);
                }
                item.PropertyName = base.GetFullPropertyName(manager) + ".Name";
                errors.Add(item);
            }
            if (string.IsNullOrEmpty(bind.Path))
            {
                item = new ValidationError(SR.GetString("Error_PathNotSetForActivitySource"), 0x12b)
                {
                    PropertyName = base.GetFullPropertyName(manager) + ".Path"
                };
                errors.Add(item);
            }
            if ((refActivity != null) && (errors.Count == 0))
            {
                string path       = bind.Path;
                string str2       = string.Empty;
                int    startIndex = path.IndexOfAny(new char[] { '.', '/', '[' });
                if (startIndex != -1)
                {
                    str2 = path.Substring(startIndex);
                    str2 = str2.StartsWith(".") ? str2.Substring(1) : str2;
                    path = path.Substring(0, startIndex);
                }
                Type       baseType   = BindHelpers.GetBaseType(manager, validationContext);
                MemberInfo memberInfo = null;
                Type       srcType    = null;
                if (!string.IsNullOrEmpty(path))
                {
                    srcType = BindValidatorHelper.GetActivityType(manager, refActivity);
                    if (srcType != null)
                    {
                        memberInfo = MemberBind.GetMemberInfo(srcType, path);
                        if ((memberInfo == null) && str2.StartsWith("[", StringComparison.Ordinal))
                        {
                            string str3  = bind.Path.Substring(startIndex);
                            int    index = str3.IndexOf(']');
                            if (index != -1)
                            {
                                string str4 = str3.Substring(0, index + 1);
                                str2 = ((index + 1) < str3.Length) ? str3.Substring(index + 1) : string.Empty;
                                str2 = str2.StartsWith(".") ? str2.Substring(1) : str2;
                                str3 = str4;
                            }
                            path       = path + str3;
                            memberInfo = MemberBind.GetMemberInfo(srcType, path);
                        }
                    }
                }
                Validator validator = null;
                object    obj2      = null;
                if (memberInfo != null)
                {
                    string str5 = !string.IsNullOrEmpty(refActivity.QualifiedName) ? refActivity.QualifiedName : bind.Name;
                    if (memberInfo is FieldInfo)
                    {
                        obj2      = new FieldBind(str5 + "." + path, str2);
                        validator = new FieldBindValidator();
                    }
                    else if (memberInfo is MethodInfo)
                    {
                        if (typeof(Delegate).IsAssignableFrom(baseType))
                        {
                            obj2      = new MethodBind(str5 + "." + path);
                            validator = new MethodBindValidator();
                        }
                        else
                        {
                            item = new ValidationError(SR.GetString("Error_InvalidMemberType", new object[] { path, base.GetFullPropertyName(manager) }), 0x629)
                            {
                                PropertyName = base.GetFullPropertyName(manager)
                            };
                            errors.Add(item);
                        }
                    }
                    else if (memberInfo is PropertyInfo)
                    {
                        if (refActivity == activity)
                        {
                            obj2      = new PropertyBind(str5 + "." + path, str2);
                            validator = new PropertyBindValidator();
                        }
                        else
                        {
                            obj2      = bind;
                            validator = this;
                        }
                    }
                    else if (memberInfo is EventInfo)
                    {
                        obj2      = bind;
                        validator = this;
                    }
                }
                else if (((memberInfo == null) && (baseType != null)) && typeof(Delegate).IsAssignableFrom(baseType))
                {
                    obj2      = bind;
                    validator = this;
                }
                if ((validator != null) && (obj2 != null))
                {
                    if ((validator == this) && (obj2 is ActivityBind))
                    {
                        errors.AddRange(this.ValidateActivityBind(manager, obj2));
                        return(errors);
                    }
                    errors.AddRange(validator.Validate(manager, obj2));
                    return(errors);
                }
                if (item == null)
                {
                    item = new ValidationError(SR.GetString("Error_PathCouldNotBeResolvedToMember", new object[] { bind.Path, !string.IsNullOrEmpty(refActivity.QualifiedName) ? refActivity.QualifiedName : refActivity.GetType().Name }), 0x60d)
                    {
                        PropertyName = base.GetFullPropertyName(manager)
                    };
                    errors.Add(item);
                }
            }
            return(errors);
        }
 internal static ValidationErrorCollection ValidateUniqueIdentifiers(Activity rootActivity)
 {
     if (rootActivity == null)
     {
         throw new ArgumentNullException("rootActivity");
     }
     Hashtable hashtable = new Hashtable();
     ValidationErrorCollection errors = new ValidationErrorCollection();
     Queue queue = new Queue();
     queue.Enqueue(rootActivity);
     while (queue.Count > 0)
     {
         Activity activity = (Activity) queue.Dequeue();
         if (activity.Enabled)
         {
             if (hashtable.ContainsKey(activity.QualifiedName))
             {
                 ValidationError item = new ValidationError(SR.GetString("Error_DuplicatedActivityID", new object[] { activity.QualifiedName }), 0x602) {
                     PropertyName = "Name"
                 };
                 item.UserData[typeof(Activity)] = activity;
                 errors.Add(item);
             }
             else
             {
                 hashtable.Add(activity.QualifiedName, activity);
             }
             if ((activity is CompositeActivity) && ((activity.Parent == null) || !Helpers.IsCustomActivity(activity as CompositeActivity)))
             {
                 foreach (Activity activity2 in Helpers.GetAllEnabledActivities((CompositeActivity) activity))
                 {
                     queue.Enqueue(activity2);
                 }
             }
         }
     }
     return errors;
 }
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            Activity activity = obj as Activity;

            if (activity == null)
            {
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "obj");
            }

            WorkflowTransactionOptions atomicTransaction = TransactedContextFilter.GetTransactionOptions(activity);

            if (atomicTransaction != null)
            {
                // Atomic scopes can't have exception handlers.
                CompositeActivity exceptionHandlers = FaultAndCancellationHandlingFilter.GetFaultHandlers(activity);
                if (exceptionHandlers != null)
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_AtomicScopeWithFaultHandlersActivityDecl, activity.Name), ErrorNumbers.Error_AtomicScopeWithFaultHandlersActivityDecl);
                    validationErrors.Add(error);
                }

                // Atomic scopes can't have cancel handlers.
                Activity cancellationHandler = FaultAndCancellationHandlingFilter.GetCancellationHandler(activity);
                if (cancellationHandler != null)
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_AtomicScopeWithCancellationHandlerActivity, activity.Name), ErrorNumbers.Error_AtomicScopeWithCancellationHandlerActivity);
                    validationErrors.Add(error);
                }

                // check that this transaction scope is not nested inside another transaction scope
                Activity parent = activity.Parent;
                while (parent != null)
                {
                    if (parent.SupportsTransaction)
                    {
                        validationErrors.Add(new ValidationError(SR.GetString(SR.Error_AtomicScopeNestedInNonLRT), ErrorNumbers.Error_AtomicScopeNestedInNonLRT));
                        break;
                    }
                    parent = parent.Parent;
                }

                // check that an activity with PersistOnClose/SupportsTransaction/ICompensatableActivity attribute is not nested inside the transaction scope
                Queue <Activity> nestedEnabledActivities = new Queue <Activity>(Helpers.GetAllEnabledActivities((CompositeActivity)activity));
                while (nestedEnabledActivities.Count > 0)
                {
                    Activity nestedEnabledActivity = nestedEnabledActivities.Dequeue();
                    if (nestedEnabledActivity.PersistOnClose)
                    {
                        validationErrors.Add(new ValidationError(SR.GetString(SR.Error_LRTScopeNestedInNonLRT), ErrorNumbers.Error_LRTScopeNestedInNonLRT));
                        break;
                    }
                    if (nestedEnabledActivity is ICompensatableActivity)
                    {
                        validationErrors.Add(new ValidationError(SR.GetString(SR.Error_NestedCompensatableActivity, nestedEnabledActivity.QualifiedName), ErrorNumbers.Error_NestedCompensatableActivity));
                        break;
                    }

                    if (nestedEnabledActivity is CompositeActivity)
                    {
                        foreach (Activity nestedEnabledActivity2 in Helpers.GetAllEnabledActivities((CompositeActivity)nestedEnabledActivity))
                        {
                            nestedEnabledActivities.Enqueue(nestedEnabledActivity2);
                        }
                    }
                }

                // check timeout property
                if (atomicTransaction.TimeoutDuration.Ticks < 0)
                {
                    ValidationError timeoutError = new ValidationError(SR.GetString(SR.Error_NegativeValue, new object[] { atomicTransaction.TimeoutDuration.ToString(), "TimeoutDuration" }), ErrorNumbers.Error_NegativeValue);
                    timeoutError.PropertyName = "TimeoutDuration";
                    validationErrors.Add(timeoutError);
                }
            }
            return(validationErrors);
        }
 public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
 {
     ValidationErrorCollection errors = base.Validate(manager, obj);
     WebServiceOutputActivity activity = obj as WebServiceOutputActivity;
     if (activity == null)
     {
         throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(WebServiceOutputActivity).FullName }), "obj");
     }
     if (!Helpers.IsActivityLocked(activity))
     {
         List<ParameterInfo> list;
         List<ParameterInfo> list2;
         WebServiceInputActivity activity2 = null;
         if (string.IsNullOrEmpty(activity.InputActivityName))
         {
             errors.Add(ValidationError.GetNotSetValidationError("InputActivityName"));
             return errors;
         }
         ITypeProvider service = (ITypeProvider) manager.GetService(typeof(ITypeProvider));
         if (service == null)
         {
             throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName }));
         }
         bool flag = false;
         foreach (Activity activity3 in WebServiceActivityHelpers.GetPreceedingActivities(activity))
         {
             if (((activity3 is WebServiceOutputActivity) && (string.Compare(((WebServiceOutputActivity) activity3).InputActivityName, activity.InputActivityName, StringComparison.Ordinal) == 0)) || ((activity3 is WebServiceFaultActivity) && (string.Compare(((WebServiceFaultActivity) activity3).InputActivityName, activity.InputActivityName, StringComparison.Ordinal) == 0)))
             {
                 if (activity3 is WebServiceOutputActivity)
                 {
                     errors.Add(new ValidationError(SR.GetString("Error_DuplicateWebServiceResponseFound", new object[] { activity3.QualifiedName, activity.InputActivityName }), 0x56a));
                     return errors;
                 }
                 errors.Add(new ValidationError(SR.GetString("Error_DuplicateWebServiceFaultFound", new object[] { activity3.QualifiedName, activity.InputActivityName }), 0x574));
                 return errors;
             }
         }
         foreach (Activity activity4 in WebServiceActivityHelpers.GetPreceedingActivities(activity))
         {
             if (string.Compare(activity4.QualifiedName, activity.InputActivityName, StringComparison.Ordinal) == 0)
             {
                 if (activity4 is WebServiceInputActivity)
                 {
                     activity2 = activity4 as WebServiceInputActivity;
                     flag = true;
                     break;
                 }
                 flag = false;
                 errors.Add(new ValidationError(SR.GetString("Error_WebServiceReceiveNotValid", new object[] { activity.InputActivityName }), 0x564));
                 return errors;
             }
         }
         if (!flag)
         {
             errors.Add(new ValidationError(SR.GetString("Error_WebServiceReceiveNotFound", new object[] { activity.InputActivityName }), 0x55e));
             return errors;
         }
         Type interfaceType = null;
         if (activity2.InterfaceType != null)
         {
             interfaceType = service.GetType(activity2.InterfaceType.AssemblyQualifiedName);
         }
         if (interfaceType == null)
         {
             errors.Add(new ValidationError(SR.GetString("Error_WebServiceReceiveNotConfigured", new object[] { activity2.Name }), 0x566));
             return errors;
         }
         if (string.IsNullOrEmpty(activity2.MethodName))
         {
             errors.Add(new ValidationError(SR.GetString("Error_WebServiceReceiveNotConfigured", new object[] { activity2.Name }), 0x566));
             return errors;
         }
         MethodInfo interfaceMethod = Helpers.GetInterfaceMethod(interfaceType, activity2.MethodName);
         if (interfaceMethod == null)
         {
             errors.Add(new ValidationError(SR.GetString("Error_WebServiceReceiveNotConfigured", new object[] { activity2.Name }), 0x566));
             return errors;
         }
         ValidationErrorCollection errors2 = WebServiceActivityHelpers.ValidateParameterTypes(interfaceMethod);
         if (errors2.Count > 0)
         {
             foreach (ValidationError error in errors2)
             {
                 error.PropertyName = "InputActivityName";
             }
             errors.AddRange(errors2);
             return errors;
         }
         WebServiceActivityHelpers.GetParameterInfo(interfaceMethod, out list, out list2);
         if (list2.Count == 0)
         {
             errors.Add(new ValidationError(SR.GetString("Error_WebServiceResponseNotNeeded"), 0x565));
             return errors;
         }
         foreach (ParameterInfo info2 in list2)
         {
             string name = info2.Name;
             Type type2 = info2.ParameterType.IsByRef ? info2.ParameterType.GetElementType() : info2.ParameterType;
             if (info2.Position == -1)
             {
                 name = "(ReturnValue)";
             }
             object binding = null;
             if (activity.ParameterBindings.Contains(name))
             {
                 if (activity.ParameterBindings[name].IsBindingSet(WorkflowParameterBinding.ValueProperty))
                 {
                     binding = activity.ParameterBindings[name].GetBinding(WorkflowParameterBinding.ValueProperty);
                 }
                 else
                 {
                     binding = activity.ParameterBindings[name].GetValue(WorkflowParameterBinding.ValueProperty);
                 }
             }
             if (!type2.IsPublic || !type2.IsSerializable)
             {
                 ValidationError item = new ValidationError(SR.GetString("Error_TypeNotPublicSerializable", new object[] { name, type2.FullName }), 0x567) {
                     PropertyName = (string.Compare(name, "(ReturnValue)", StringComparison.Ordinal) == 0) ? name : ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(activity2.GetType(), name)
                 };
                 errors.Add(item);
             }
             else if (!activity.ParameterBindings.Contains(name) || (binding == null))
             {
                 ValidationError notSetValidationError = ValidationError.GetNotSetValidationError(name);
                 notSetValidationError.PropertyName = (string.Compare(name, "(ReturnValue)", StringComparison.Ordinal) == 0) ? name : ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(activity2.GetType(), name);
                 errors.Add(notSetValidationError);
             }
             else
             {
                 AccessTypes read = AccessTypes.Read;
                 if ((info2.IsOut || info2.IsRetval) || (info2.Position == -1))
                 {
                     read = AccessTypes.Write;
                 }
                 ValidationErrorCollection errors3 = System.Workflow.Activities.Common.ValidationHelpers.ValidateProperty(manager, activity, binding, new PropertyValidationContext(activity.ParameterBindings[name], null, name), new BindValidationContext(info2.ParameterType.IsByRef ? info2.ParameterType.GetElementType() : info2.ParameterType, read));
                 foreach (ValidationError error4 in errors3)
                 {
                     if (string.Compare(name, "(ReturnValue)", StringComparison.Ordinal) != 0)
                     {
                         error4.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(activity2.GetType(), name);
                     }
                 }
                 errors.AddRange(errors3);
             }
         }
         if (activity.ParameterBindings.Count > list2.Count)
         {
             errors.Add(new ValidationError(SR.GetString("Warning_AdditionalBindingsFound"), 0x630, true));
         }
     }
     return errors;
 }
Пример #38
0
        private ValidationErrorCollection ValidateActivity(ValidationManager manager, ActivityBind bind, BindValidationContext validationContext)
        {
            ValidationError           item   = null;
            ValidationErrorCollection errors = new ValidationErrorCollection();
            Activity activity = manager.Context[typeof(Activity)] as Activity;

            if (activity == null)
            {
                throw new InvalidOperationException(SR.GetString("Error_ContextStackItemMissing", new object[] { typeof(Activity).Name }));
            }
            Activity request = Helpers.ParseActivityForBind(activity, bind.Name);

            if (request == null)
            {
                item = bind.Name.StartsWith("/", StringComparison.Ordinal) ? new ValidationError(SR.GetString("Error_CannotResolveRelativeActivity", new object[] { bind.Name }), 0x128) : new ValidationError(SR.GetString("Error_CannotResolveActivity", new object[] { bind.Name }), 0x129);
                item.PropertyName = base.GetFullPropertyName(manager) + ".Name";
            }
            else if ((bind.Path == null) || (bind.Path.Length == 0))
            {
                item = new ValidationError(SR.GetString("Error_PathNotSetForActivitySource"), 0x12b)
                {
                    PropertyName = base.GetFullPropertyName(manager) + ".Path"
                };
            }
            else
            {
                if (!bind.Name.StartsWith("/", StringComparison.Ordinal) && !ValidationHelpers.IsActivitySourceInOrder(request, activity))
                {
                    item = new ValidationError(SR.GetString("Error_BindActivityReference", new object[] { request.QualifiedName, activity.QualifiedName }), 0x12a, true)
                    {
                        PropertyName = base.GetFullPropertyName(manager) + ".Name"
                    };
                }
                IDesignerHost          service = manager.GetService(typeof(IDesignerHost)) as IDesignerHost;
                WorkflowDesignerLoader loader  = manager.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;
                if ((service != null) && (loader != null))
                {
                    Type srcType = null;
                    if (service.RootComponent == request)
                    {
                        ITypeProvider provider = manager.GetService(typeof(ITypeProvider)) as ITypeProvider;
                        if (provider == null)
                        {
                            throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName }));
                        }
                        srcType = provider.GetType(service.RootComponentClassName);
                    }
                    else
                    {
                        request.GetType();
                    }
                    if (srcType != null)
                    {
                        MemberInfo memberInfo = MemberBind.GetMemberInfo(srcType, bind.Path);
                        if ((memberInfo == null) || ((memberInfo is PropertyInfo) && !(memberInfo as PropertyInfo).CanRead))
                        {
                            item = new ValidationError(SR.GetString("Error_InvalidMemberPath", new object[] { request.QualifiedName, bind.Path }), 300)
                            {
                                PropertyName = base.GetFullPropertyName(manager) + ".Path"
                            };
                        }
                        else
                        {
                            Type memberType = null;
                            if (memberInfo is FieldInfo)
                            {
                                memberType = ((FieldInfo)memberInfo).FieldType;
                            }
                            else if (memberInfo is PropertyInfo)
                            {
                                memberType = ((PropertyInfo)memberInfo).PropertyType;
                            }
                            else if (memberInfo is EventInfo)
                            {
                                memberType = ((EventInfo)memberInfo).EventHandlerType;
                            }
                            if (!DoesTargetTypeMatch(validationContext.TargetType, memberType, validationContext.Access))
                            {
                                if (typeof(WorkflowParameterBinding).IsAssignableFrom(memberInfo.DeclaringType))
                                {
                                    item = new ValidationError(SR.GetString("Warning_ParameterBinding", new object[] { bind.Path, request.QualifiedName, validationContext.TargetType.FullName }), 0x624, true)
                                    {
                                        PropertyName = base.GetFullPropertyName(manager) + ".Path"
                                    };
                                }
                                else
                                {
                                    item = new ValidationError(SR.GetString("Error_TargetTypeMismatch", new object[] { memberInfo.Name, memberType.FullName, validationContext.TargetType.FullName }), 0x12d)
                                    {
                                        PropertyName = base.GetFullPropertyName(manager) + ".Path"
                                    };
                                }
                            }
                        }
                    }
                }
                else
                {
                    MemberInfo info2 = MemberBind.GetMemberInfo(request.GetType(), bind.Path);
                    if ((info2 == null) || ((info2 is PropertyInfo) && !(info2 as PropertyInfo).CanRead))
                    {
                        item = new ValidationError(SR.GetString("Error_InvalidMemberPath", new object[] { request.QualifiedName, bind.Path }), 300)
                        {
                            PropertyName = base.GetFullPropertyName(manager) + ".Path"
                        };
                    }
                    else
                    {
                        DependencyProperty dependencyProperty = DependencyProperty.FromName(info2.Name, info2.DeclaringType);
                        object             obj2 = BindHelpers.ResolveActivityPath(request, bind.Path);
                        if (obj2 == null)
                        {
                            Type fromType = null;
                            if (info2 is FieldInfo)
                            {
                                fromType = ((FieldInfo)info2).FieldType;
                            }
                            else if (info2 is PropertyInfo)
                            {
                                fromType = ((PropertyInfo)info2).PropertyType;
                            }
                            else if (info2 is EventInfo)
                            {
                                fromType = ((EventInfo)info2).EventHandlerType;
                            }
                            if (!TypeProvider.IsAssignable(typeof(ActivityBind), fromType) && !DoesTargetTypeMatch(validationContext.TargetType, fromType, validationContext.Access))
                            {
                                if (typeof(WorkflowParameterBinding).IsAssignableFrom(info2.DeclaringType))
                                {
                                    item = new ValidationError(SR.GetString("Warning_ParameterBinding", new object[] { bind.Path, request.QualifiedName, validationContext.TargetType.FullName }), 0x624, true)
                                    {
                                        PropertyName = base.GetFullPropertyName(manager) + ".Path"
                                    };
                                }
                                else
                                {
                                    item = new ValidationError(SR.GetString("Error_TargetTypeMismatch", new object[] { info2.Name, fromType.FullName, validationContext.TargetType.FullName }), 0x12d)
                                    {
                                        PropertyName = base.GetFullPropertyName(manager) + ".Path"
                                    };
                                }
                            }
                        }
                        else if ((obj2 is ActivityBind) && (request.Parent != null))
                        {
                            ActivityBind         bind2   = obj2 as ActivityBind;
                            bool                 flag    = false;
                            BindRecursionContext context = manager.Context[typeof(BindRecursionContext)] as BindRecursionContext;
                            if (context == null)
                            {
                                context = new BindRecursionContext();
                                manager.Context.Push(context);
                                flag = true;
                            }
                            if (context.Contains(activity, bind))
                            {
                                item = new ValidationError(SR.GetString("Bind_ActivityDataSourceRecursionDetected"), 0x12f)
                                {
                                    PropertyName = base.GetFullPropertyName(manager) + ".Path"
                                };
                            }
                            else
                            {
                                context.Add(activity, bind);
                                PropertyValidationContext propertyValidationContext = null;
                                if (dependencyProperty != null)
                                {
                                    propertyValidationContext = new PropertyValidationContext(request, dependencyProperty);
                                }
                                else
                                {
                                    propertyValidationContext = new PropertyValidationContext(request, info2 as PropertyInfo, info2.Name);
                                }
                                errors.AddRange(ValidationHelpers.ValidateProperty(manager, request, bind2, propertyValidationContext, validationContext));
                            }
                            if (flag)
                            {
                                manager.Context.Pop();
                            }
                        }
                        else if ((validationContext.TargetType != null) && !DoesTargetTypeMatch(validationContext.TargetType, obj2.GetType(), validationContext.Access))
                        {
                            item = new ValidationError(SR.GetString("Error_TargetTypeMismatch", new object[] { info2.Name, obj2.GetType().FullName, validationContext.TargetType.FullName }), 0x12d)
                            {
                                PropertyName = base.GetFullPropertyName(manager) + ".Path"
                            };
                        }
                    }
                }
            }
            if (item != null)
            {
                errors.Add(item);
            }
            return(errors);
        }