Пример #1
0
            public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
            {
                bool propertiesValid = true;

                foreach (ModelMetadata propertyMetadata in metadata.Properties)
                {
                    foreach (ModelValidator propertyValidator in propertyMetadata.GetValidators(ValidatorProviders))
                    {
                        foreach (ModelValidationResult propertyResult in propertyValidator.Validate(metadata, container))
                        {
                            propertiesValid = false;
                            yield return new ModelValidationResult
                            {
                                MemberName = ModelBindingHelper.CreatePropertyModelName(propertyMetadata.PropertyName, propertyResult.MemberName),
                                Message = propertyResult.Message
                            };
                        }
                    }
                }

                if (propertiesValid)
                {
                    foreach (ModelValidator typeValidator in metadata.GetValidators(ValidatorProviders))
                    {
                        foreach (ModelValidationResult typeResult in typeValidator.Validate(metadata, container))
                        {
                            yield return typeResult;
                        }
                    }
                }
            }
        public IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata)
        {
            // If metadata is for a property then containerType != null && propertyName != null
            // If metadata is for a type then containerType == null && propertyName == null, so we have to use modelType for the cache key.
            Type typeForCache = metadata.ContainerType ?? metadata.ModelType;
            Tuple<Type, string> cacheKey = Tuple.Create(typeForCache, metadata.PropertyName);

            ModelValidator[] validators;
            if (!TryGetValue(cacheKey, out validators))
            {
                _cacheLock.EnterWriteLock();
                try
                {
                    // Check the cache again in case the value was computed and added to the cache while we were waiting on the write lock
                    if (!_validatorCache.TryGetValue(cacheKey, out validators))
                    {
                        // Compute validators
                        validators = metadata.GetValidators(_validatorProviders.Value).ToArray();
                        _validatorCache.Add(cacheKey, validators);
                    }
                }
                finally
                {
                    _cacheLock.ExitWriteLock();
                }
            }
            return validators;
        }
        public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
        {
            if (metadata.Model != null)
            {
                var selector = _customizations.ToValidatorSelector();
                //var interceptor = _customizations.GetInterceptor() ?? (_validator as IValidatorInterceptor);
                var context = new ValidationContext(metadata.Model, new PropertyChain(), selector);

                //if (interceptor != null)
                //{
                //    // Allow the user to provide a customized context
                //    // However, if they return null then just use the original context.
                //    context = interceptor.BeforeMvcValidation(ControllerContext, context) ?? context;
                //}

                var result = _validator.Validate(context);

                //if (interceptor != null)
                //{
                //    // allow the user to provice a custom collection of failures, which could be empty.
                //    // However, if they return null then use the original collection of failures.
                //    result = interceptor.AfterMvcValidation(ControllerContext, context, result) ?? result;
                //}

                if (!result.IsValid)
                {
                    return ConvertValidationResultToModelValidationResults(result);
                }
            }
            return Enumerable.Empty<ModelValidationResult>();
        }
Пример #4
0
        public void DefaultValues()
        {
            // Arrange
            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();

            // Act
            ModelMetadata metadata = new ModelMetadata(provider.Object, typeof(Exception), () => "model", typeof(string), "propertyName");

            // Assert
            Assert.Equal(typeof(Exception), metadata.ContainerType);
            Assert.True(metadata.ConvertEmptyStringToNull);
            Assert.Null(metadata.DataTypeName);
            Assert.Null(metadata.Description);
            Assert.Null(metadata.DisplayFormatString);
            Assert.Null(metadata.DisplayName);
            Assert.Null(metadata.EditFormatString);
            Assert.False(metadata.HideSurroundingHtml);
            Assert.Equal("model", metadata.Model);
            Assert.Equal(typeof(string), metadata.ModelType);
            Assert.Null(metadata.NullDisplayText);
            Assert.Equal(10000, metadata.Order);
            Assert.Equal("propertyName", metadata.PropertyName);
            Assert.False(metadata.IsReadOnly);
            Assert.True(metadata.RequestValidationEnabled);
            Assert.Null(metadata.ShortDisplayName);
            Assert.True(metadata.ShowForDisplay);
            Assert.True(metadata.ShowForEdit);
            Assert.Null(metadata.TemplateHint);
            Assert.Null(metadata.Watermark);
        }
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)
        {
                List<ModelValidator> results = new List<ModelValidator>();

                // Produce a validator for each validation attribute we find
                foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>())
                {
                    DataAnnotationsModelValidationFactory factory;
                    if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory))
                    {
                        factory = DefaultAttributeFactory;
                    }
                    results.Add(factory(metadata, validatorProviders, attribute));
                }

                // Produce a validator if the type supports IValidatableObject
                if (typeof(IValidatableObject).IsAssignableFrom(metadata.ModelType))
                {
                    DataAnnotationsValidatableObjectAdapterFactory factory;
                    if (!ValidatableFactories.TryGetValue(metadata.ModelType, out factory))
                    {
                        factory = DefaultValidatableFactory;
                    }
                    results.Add(factory(metadata, validatorProviders));
                }

                return results;
            }
Пример #6
0
        public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
        {
            if (metadata.Model is string)
            {
                var dirty = (string) metadata.Model;
                var sanitized = Sanitizer.GetSafeHtmlFragment(dirty);
                if (!dirty.Equals(sanitized))
                {
                    // Revert HTML encoded special characters
                    sanitized = sanitized.Replace("&lt;", "<");
                    sanitized = sanitized.Replace("&gt;", ">");
                    sanitized = sanitized.Replace("&amp;", "&");
                    sanitized = sanitized.Replace("&quot;", "\"");

                    if (!dirty.Equals(sanitized))
                    {
                        yield return new ModelValidationResult
                        {
                            MemberName = string.Empty,
                            Message = "A potentially dangerous value was detected from the client."
                        };
                    }
                }
            }
        }
Пример #7
0
 public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
 {
     if (metadata.Model is string)
     {
         return ValidateString((string)metadata.Model, metadata.PropertyName);
     }
     return Enumerable.Empty<ModelValidationResult>();
 }
 public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)
 {
     if (IsValidatingProperty(metadata))
     {
         return GetValidatorsForProperty(metadata, validatorProviders, ValidatorFactory.GetValidator(metadata.ContainerType));
     }
     return GetValidatorsForModel(
         //metadata,
         validatorProviders, ValidatorFactory.GetValidator(metadata.ModelType));
 }
        /// <summary>
        /// Gets the collection of registered <see cref="ModelValidator"/> instances.
        /// </summary>
        /// <param name="actionContext">The context.</param>
        /// <param name="metadata">The metadata.</param>
        /// <returns>A collection of registered <see cref="ModelValidator"/> instances.</returns>
        public static IEnumerable<ModelValidator> GetValidators(this HttpActionContext actionContext, ModelMetadata metadata)
        {
            if (actionContext == null)
            {
                throw Error.ArgumentNull("actionContext");
            }

            IEnumerable<ModelValidatorProvider> validatorProviders = GetValidatorProviders(actionContext);
            return validatorProviders.SelectMany(provider => provider.GetValidators(metadata, validatorProviders));
        }
        /// <summary>
        /// Gets the validators.
        /// </summary>
        /// <param name="metadata">The metadata.</param>
        /// <param name="validatorProviders">The validator providers.</param>
        /// <returns>
        /// The validators returned by the default validator providers.
        /// </returns>
        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)
        {
            var validators = this.defaultModelValidatorProviders.SelectMany(provider => provider.GetValidators(metadata, validatorProviders)).ToList();
            foreach (var modelValidator in validators)
            {
                this.kernel.Inject(modelValidator);
            }

            return validators;
        }
        public void TypeConversionErrorMessageProvider_DefaultValue()
        {
            // Arrange
            ModelMetadata metadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(int), "SomePropertyName");

            // Act
            string errorString = ModelBinderConfig.TypeConversionErrorMessageProvider(null, metadata, "some incoming value");

            // Assert
            Assert.Equal("The value 'some incoming value' is not valid for SomePropertyName.", errorString);
        }
        /// <summary>
        /// Gets a list of validators.
        /// </summary>
        /// <param name="metadata">The metadata.</param>
        /// <param name="actionContext">The context.</param>
        /// <param name="attributes">The list of validation attributes.</param>
        /// <returns>A list of validators.</returns>
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, HttpActionContext actionContext, IEnumerable<Attribute> attributes)
        {
            var validators = base.GetValidators(metadata, actionContext, attributes);
            foreach (var modelValidator in validators.OfType<DataAnnotationsModelValidator>())
            {
                var attribute = this.getAttributeMethodInfo.Invoke(modelValidator, new object[0]);
                this.kernel.Inject(attribute);
            }

            return validators;
        }
		public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container) {
		    if (metadata.Model == null) return Enumerable.Empty<ModelValidationResult>();
		    var selector = new DefaultValidatorSelector();
		    var context = new ValidationContext(metadata.Model, new PropertyChain(), selector);

		    var result = validator.Validate(context);

		    return !result.IsValid 
                ? ConvertValidationResultToModelValidationResults(result) 
                : Enumerable.Empty<ModelValidationResult>();
		}
        public void ValueRequiredErrorMessageProvider_DefaultValue()
        {
            // Arrange
            ModelMetadata metadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(int), "SomePropertyName");

            // Act
            string errorString = ModelBinderConfig.ValueRequiredErrorMessageProvider(null, metadata, "some incoming value");

            // Assert
            Assert.Equal("A value is required.", errorString);
        }
        private IEnumerable<ModelValidator> GetValidatorsForProperty(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)
        {
            ICustomTypeDescriptor typeDescriptor = GetTypeDescriptor(metadata.ContainerType);
            PropertyDescriptor property = typeDescriptor.GetProperties().Find(metadata.PropertyName, true);
            if (property == null)
            {
                throw Error.Argument("metadata", SRResources.Common_PropertyNotFound, metadata.ContainerType, metadata.PropertyName);
            }

            return GetValidators(metadata, validatorProviders, property.Attributes.OfType<Attribute>());
        }
Пример #16
0
 public ModelValidator[] GetValidators(ModelMetadata metadata)
 {
     ModelValidator[] validators;
     if (!_validatorCache.TryGetValue(metadata.CacheKey, out validators))
     {
         // Compute validators
         // There are no side-effects if the same validators are created more than once
         validators = metadata.GetValidators(_validatorProviders.Value).ToArray();
         _validatorCache.TryAdd(metadata.CacheKey, validators);
     }
     return validators;
 }
 private static bool ValidateProperties(ModelMetadata metadata, ValidationContext validationContext, string prefix)
 {
     bool isValid = true;
     foreach (ModelMetadata childMetadata in metadata.Properties)
     {
         string childPrefix = ModelBindingHelper.CreatePropertyModelName(prefix, childMetadata.PropertyName);
         if (!ValidateNodeAndChildren(childMetadata, validationContext, metadata.Model, childPrefix))
         {
             isValid = false;
         }
     }
     return isValid;
 }
		public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container) {
			if (metadata.Model != null) {
				var selector = ValidatorOptions.ValidatorSelectors.DefaultValidatorSelectorFactory();
				var context = new ValidationContext(metadata.Model, new PropertyChain(), selector);

				var result = validator.Validate(context);

				if (!result.IsValid) {
					return ConvertValidationResultToModelValidationResults(result);
				}
			}
			return Enumerable.Empty<ModelValidationResult>();
		}
 public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)
 {
     string propertyName = metadata.PropertyName;
     // if we're validating a property and not a type
     if (propertyName != null)
     {
         PropertyInfo metadataProperty = metadata.ContainerType.GetProperty(propertyName);
         if (_requiredMemberSelector.IsRequiredMember(metadataProperty))
         {
             return new ModelValidator[] { new RequiredMemberModelValidator(validatorProviders) };
         }
     }
     return new ModelValidator[0];
 }
 protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)
 {
     DataMemberAttribute dataMemberAttribute = attributes.OfType<DataMemberAttribute>().FirstOrDefault();
     if (dataMemberAttribute != null)
     {
         // isDataContract == true iff the containter type has at least one DataContractAttribute
         bool isDataContract = GetTypeDescriptor(metadata.ContainerType).GetAttributes().OfType<DataContractAttribute>().Any();
         if (isDataContract && dataMemberAttribute.IsRequired)
         {
             return new[] { new RequiredMemberModelValidator(validatorProviders) };
         }
     }
     return new ModelValidator[0];
 }
        private ModelValidator GetModelValidator(ModelMetadata meta, IEnumerable<ModelValidatorProvider> validatorProviders, PropertyRule rule, IPropertyValidator propertyValidator)
        {
            //var type = propertyValidator.GetType();

            FluentValidationHttpModelValidationFactory factory =
                //validatorFactories
                //.Where(x => x.Key.IsAssignableFrom(type))
                //.Select(x => x.Value)
                //.FirstOrDefault()
                //??
                ((metadata, controllerContext, description, validator) => new FluentValidationHttpPropertyValidator(metadata, controllerContext, description, validator));

            return factory(meta, validatorProviders, rule, propertyValidator);
        }
        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)
        {
            if (IsValidatingProperty(metadata)) {
                yield break;
            }

            IValidator validator = ValidatorFactory.GetValidator(metadata.ModelType);

            if (validator == null) {
                yield break;
            }

            yield return new FluentValidationModelValidator(validatorProviders, validator);
        }
Пример #23
0
        public void ConstructorSetsProperties()
        {
            // Arrange
            ModelMetadata modelMetadata = GetModelMetadata();
            ModelMetadata[] propertyMetadata = new ModelMetadata[0];

            // Act
            ComplexModelDto dto = new ComplexModelDto(modelMetadata, propertyMetadata);

            // Assert
            Assert.Equal(modelMetadata, dto.ModelMetadata);
            Assert.Equal(propertyMetadata, dto.PropertyMetadata.ToArray());
            Assert.Empty(dto.Results);
        }
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)
        {
            // Types cannot be required; only properties can
            if (metadata.ContainerType == null || String.IsNullOrEmpty(metadata.PropertyName))
            {
                return Enumerable.Empty<ModelValidator>();
            }

            if (IsRequiredDataMember(metadata.ContainerType, attributes))
            {
                return new[] { new RequiredMemberModelValidator(validatorProviders) };
            }

            return Enumerable.Empty<ModelValidator>();
        }
Пример #25
0
        public ModelValidationNode(ModelMetadata modelMetadata, string modelStateKey, IEnumerable<ModelValidationNode> childNodes)
        {
            if (modelMetadata == null)
            {
                throw Error.ArgumentNull("modelMetadata");
            }
            if (modelStateKey == null)
            {
                throw Error.ArgumentNull("modelStateKey");
            }

            ModelMetadata = modelMetadata;
            ModelStateKey = modelStateKey;
            ChildNodes = (childNodes != null) ? childNodes.ToList() : new List<ModelValidationNode>();
        }
Пример #26
0
        public ComplexModelDto(ModelMetadata modelMetadata, IEnumerable<ModelMetadata> propertyMetadata)
        {
            if (modelMetadata == null)
            {
                throw Error.ArgumentNull("modelMetadata");
            }

            if (propertyMetadata == null)
            {
                throw Error.ArgumentNull("propertyMetadata");
            }

            ModelMetadata = modelMetadata;
            PropertyMetadata = new Collection<ModelMetadata>(propertyMetadata.ToList());
            Results = new Dictionary<ModelMetadata, ComplexModelDtoResult>();
        }
        public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
        {
            // Per the WCF RIA Services team, instance can never be null (if you have
            // no parent, you pass yourself for the "instance" parameter).
            ValidationContext context = new ValidationContext(container ?? metadata.Model, null, null);
            context.DisplayName = metadata.GetDisplayName();

            ValidationResult result = Attribute.GetValidationResult(metadata.Model, context);

            if (result != ValidationResult.Success)
            {
                return new ModelValidationResult[] { new ModelValidationResult { Message = result.ErrorMessage } };
            }

            return new ModelValidationResult[0];
        }
        protected bool ValidateNodeAndChildren(ModelMetadata metadata, ValidationContext validationContext, object container)
        {
            object model = metadata.Model;
            bool isValid = true;

            // Optimization: we don't need to recursively traverse the graph for null and primitive types
            if (model == null || TypeHelper.IsSimpleType(model.GetType()))
            {
                return ShallowValidate(metadata, validationContext, container);
            }

            // Check to avoid infinite recursion. This can happen with cycles in an object graph.
            if (validationContext.Visited.Contains(model))
            {
                return true;
            }
            validationContext.Visited.Add(model);

            var custom = CustomValidation(metadata, validationContext, model);
            if (custom != null)
            {
                isValid = custom.Value;
            }
            else
            {
                // Validate the children first - depth-first traversal
                IEnumerable enumerableModel = model as IEnumerable;
                if (enumerableModel == null)
                {
                    isValid = ValidateProperties(metadata, validationContext);
                }
                else
                {
                    isValid = ValidateElements(enumerableModel, validationContext);
                }
                if (isValid)
                {
                    // Don't bother to validate this node if children failed.
                    isValid = ShallowValidate(metadata, validationContext, container);
                }
            }

            // Pop the object so that it can be validated again in a different path
            validationContext.Visited.Remove(model);

            return isValid;
        }
Пример #29
0
        public IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata)
        {
            // If metadata is for a property then containerType != null && propertyName != null
            // If metadata is for a type then containerType == null && propertyName == null, so we have to use modelType for the cache key.
            Type typeForCache = metadata.ContainerType ?? metadata.ModelType;
            Tuple<Type, string> cacheKey = Tuple.Create(typeForCache, metadata.PropertyName);

            ModelValidator[] validators;
            if (!_validatorCache.TryGetValue(cacheKey, out validators))
            {
                // Compute validators
                // There are no side-effects if the same validators are created more than once
                validators = metadata.GetValidators(_validatorProviders.Value).ToArray();
                _validatorCache.TryAdd(cacheKey, validators);
            }
            return validators;
        }
        public void DefaultValues()
        {
            // Arrange
            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();

            // Act
            ModelMetadata metadata = new ModelMetadata(provider.Object, typeof(Exception), () => "model", typeof(string), "propertyName");

            // Assert
            Assert.Equal(typeof(Exception), metadata.ContainerType);
            Assert.True(metadata.ConvertEmptyStringToNull);
            Assert.Null(metadata.Description);
            Assert.Equal("model", metadata.Model);
            Assert.Equal(typeof(string), metadata.ModelType);
            Assert.Equal("propertyName", metadata.PropertyName);
            Assert.False(metadata.IsReadOnly);
        }