/// <summary>
        /// Gets the <see cref="PropertyValidator"/> instances for the specified <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The <see cref="Type"/> that the validators should be retrieved for.</param>
        /// <returns>An <see cref="IEnumerable{T}"/> instance, containing <see cref="IPropertyValidator"/> objects.</returns>
        public IEnumerable<IPropertyValidator> GetValidators(Type type)
        {
            var typeDescriptor =
                new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);

            var propertyDescriptors =
                typeDescriptor.GetProperties();

            var results =
                new List<IPropertyValidator>();

            foreach (PropertyDescriptor descriptor in propertyDescriptors)
            {
                var attributes =
                    descriptor.Attributes.OfType<ValidationAttribute>();

                var validator =
                    new PropertyValidator
                    {
                        AttributeAdaptors = this.GetAttributeAdaptors(attributes),
                        Descriptor = descriptor
                    };

                results.Add(validator);
            }

            return results;
        }
Пример #2
0
        /// <summary>
        /// Gets the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public static ICustomTypeDescriptor Get(Type type)
        {
            try
            {
                locker.EnterReadLock();
                var metadataType = hashtable[type] as Type;
                ICustomTypeDescriptor descriptor = null;
                if (metadataType != null)
                {
                    var instance = TypeActivator.CreateInstance(metadataType);
                    if (instance != null)
                    {
                        // Order to get the metadata type instance from DI.
                        metadataType = instance.GetType();
                        descriptor = new AssociatedMetadataTypeTypeDescriptionProvider(type, metadataType).GetTypeDescriptor(type);
                    }
                }

                return descriptor;
            }
            finally
            {
                locker.ExitReadLock();
            }
        }
        protected virtual ICustomTypeDescriptor GetTypeDescriptor(BindingContext context)
        {
            AssociatedMetadataTypeTypeDescriptionProvider provider =
                new AssociatedMetadataTypeTypeDescriptionProvider(context.ModelType);

            return provider.GetTypeDescriptor(context.ModelType, context.Model);
        }
Пример #4
0
 /// <summary>
 /// Validates the specified validation context.
 /// </summary>
 /// <param name="validationContext">The validation context.</param>
 /// <param name="metadata">The metadata.</param>
 /// <returns></returns>
 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext, ModelMetadata metadata) {
     if (!metadata.IsRequired || VirtualPath != null) yield break;
     var customTypeDescriptor = new AssociatedMetadataTypeTypeDescriptionProvider(metadata.ContainerType).GetTypeDescriptor(metadata.ContainerType);
     if (customTypeDescriptor == null) yield break;
     var descriptor = customTypeDescriptor.GetProperties().Find(metadata.PropertyName, true);
     var req = (new List<Attribute>(descriptor.Attributes.OfType<Attribute>())).OfType<RequiredAttribute>().FirstOrDefault();
     if (req != null) yield return new ValidationResult(req.FormatErrorMessage(metadata.DisplayName));
 }
Пример #5
0
        private static void RegisterModelMetadata(object model)
        {
            var modelType = model.GetType();
            var typeAttributes = System.Attribute.GetCustomAttributes(modelType);
            var modelMetadata = (MetadataTypeAttribute)typeAttributes.FirstOrDefault(x => x is MetadataTypeAttribute);

            if (modelMetadata != null)
            {
                var provider = new AssociatedMetadataTypeTypeDescriptionProvider(modelType, modelMetadata.MetadataClassType);

                TypeDescriptor.AddProviderTransparent(provider, modelType);
            }
        }
        /// <summary>
        /// Gets the <see cref="PropertyValidator"/> instances for the specified <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The <see cref="Type"/> that the validators should be retrieved for.</param>
        /// <returns>An <see cref="IEnumerable{T}"/> instance, containing <see cref="IPropertyValidator"/> objects.</returns>
        public IEnumerable<IPropertyValidator> GetValidators(Type type)
        {
            var typeDescriptor =
                new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);

            var results =
                new List<IPropertyValidator>();

            results.Add(this.GetTypeValidator(typeDescriptor));
            results.AddRange(this.GetPropertyValidators(typeDescriptor));

            return results;
        }
		public void GetTypeDescriptor ()
		{
			var v = new AssociatedMetadataTypeTypeDescriptionProvider (typeof (string));

			Assert.IsTrue (v != null, "#A1");

			string s = "test";
			var o = v.GetTypeDescriptor (s.GetType (), s);
			Assert.IsTrue (o != null, "#B1");

			Type oType = o.GetType ();
			Assert.AreEqual ("System.ComponentModel.DataAnnotations.AssociatedMetadataTypeTypeDescriptor", oType.ToString (), "#C1");
			Assert.IsTrue (typeof (ICustomTypeDescriptor).IsAssignableFrom (oType), "#C2");
			Assert.IsTrue (typeof (CustomTypeDescriptor).IsAssignableFrom (oType), "#C3");
		}
Пример #8
0
        /// <inheritdoc/>
        public Task ValidateChangeSetItemAsync(
            SubmitContext context,
            ChangeSetItem item,
            Collection <ChangeSetItemValidationResult> validationResults,
            CancellationToken cancellationToken)
        {
            Ensure.NotNull(validationResults, "validationResults");
            DataModificationItem dataModificationItem = item as DataModificationItem;

            if (dataModificationItem != null)
            {
                object resource = dataModificationItem.Resource;

                // TODO GitHubIssue#50 : should this PropertyDescriptorCollection be cached?
                PropertyDescriptorCollection properties =
                    new DataAnnotations.AssociatedMetadataTypeTypeDescriptionProvider(resource.GetType())
                    .GetTypeDescriptor(resource).GetProperties();

                DataAnnotations.ValidationContext validationContext = new DataAnnotations.ValidationContext(resource);

                foreach (PropertyDescriptor property in properties)
                {
                    validationContext.MemberName = property.Name;

                    IEnumerable <DataAnnotations.ValidationAttribute> validationAttributes =
                        property.Attributes.OfType <DataAnnotations.ValidationAttribute>();
                    foreach (DataAnnotations.ValidationAttribute validationAttribute in validationAttributes)
                    {
                        object value = property.GetValue(resource);
                        DataAnnotations.ValidationResult validationResult =
                            validationAttribute.GetValidationResult(value, validationContext);
                        if (validationResult != DataAnnotations.ValidationResult.Success)
                        {
                            validationResults.Add(new ChangeSetItemValidationResult()
                            {
                                Id           = validationAttribute.GetType().FullName,
                                Message      = validationResult.ErrorMessage,
                                Severity     = EventLevel.Error,
                                Target       = resource,
                                PropertyName = property.Name
                            });
                        }
                    }
                }
            }

            return(Task.WhenAll());
        }
        /// <inheritdoc/>
        public Task ValidateEntityAsync(
            SubmitContext context,
            ChangeSetEntry entry,
            ValidationResults validationResults,
            CancellationToken cancellationToken)
        {
            Ensure.NotNull(validationResults, "validationResults");
            DataModificationEntry dataModificationEntry = entry as DataModificationEntry;

            if (dataModificationEntry != null)
            {
                object entity = dataModificationEntry.Entity;

                // TODO GitHubIssue#50 : should this PropertyDescriptorCollection be cached?
                PropertyDescriptorCollection properties =
                    new DataAnnotations.AssociatedMetadataTypeTypeDescriptionProvider(entity.GetType())
                    .GetTypeDescriptor(entity).GetProperties();

                DataAnnotations.ValidationContext validationContext = new DataAnnotations.ValidationContext(entity);

                foreach (PropertyDescriptor property in properties)
                {
                    validationContext.MemberName = property.Name;

                    IEnumerable <DataAnnotations.ValidationAttribute> validationAttributes =
                        property.Attributes.OfType <DataAnnotations.ValidationAttribute>();
                    foreach (DataAnnotations.ValidationAttribute validationAttribute in validationAttributes)
                    {
                        object value = property.GetValue(entity);
                        DataAnnotations.ValidationResult validationResult =
                            validationAttribute.GetValidationResult(value, validationContext);
                        if (validationResult != DataAnnotations.ValidationResult.Success)
                        {
                            validationResults.Add(new ValidationResult()
                            {
                                Id           = validationAttribute.GetType().FullName,
                                Message      = validationResult.ErrorMessage,
                                Severity     = ValidationSeverity.Error,
                                Target       = entity,
                                PropertyName = property.Name
                            });
                        }
                    }
                }
            }

            return(Task.WhenAll());
        }
Пример #10
0
        private object BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            //针对目标类型创建一个空Model对象
            Type modelType = bindingContext.ModelType;
            object model = this.CreateModel(controllerContext, bindingContext, modelType);
            bindingContext.ModelMetadata.Model = model;

            //针对每个描述属性的PropertyDescriptor对象调用BindProperty方法对相应属性赋值
            ICustomTypeDescriptor modelTypeDescriptor = new AssociatedMetadataTypeTypeDescriptionProvider(modelType).GetTypeDescriptor(modelType);
            PropertyDescriptorCollection propertyDescriptors = modelTypeDescriptor.GetProperties();
            foreach (PropertyDescriptor propertyDescriptor in propertyDescriptors)
            {
                this.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
            return model;
        }
        /// <inheritdoc/>
        public Task ValidateChangeSetItemAsync(
            SubmitContext context,
            ChangeSetItem item,
            Collection<ChangeSetItemValidationResult> validationResults,
            CancellationToken cancellationToken)
        {
            Ensure.NotNull(validationResults, "validationResults");
            DataModificationItem dataModificationItem = item as DataModificationItem;
            if (dataModificationItem != null)
            {
                object resource = dataModificationItem.Resource;

                // TODO GitHubIssue#50 : should this PropertyDescriptorCollection be cached?
                PropertyDescriptorCollection properties =
                    new DataAnnotations.AssociatedMetadataTypeTypeDescriptionProvider(resource.GetType())
                    .GetTypeDescriptor(resource).GetProperties();

                DataAnnotations.ValidationContext validationContext = new DataAnnotations.ValidationContext(resource);

                foreach (PropertyDescriptor property in properties)
                {
                    validationContext.MemberName = property.Name;

                    IEnumerable<DataAnnotations.ValidationAttribute> validationAttributes =
                        property.Attributes.OfType<DataAnnotations.ValidationAttribute>();
                    foreach (DataAnnotations.ValidationAttribute validationAttribute in validationAttributes)
                    {
                        object value = property.GetValue(resource);
                        DataAnnotations.ValidationResult validationResult =
                            validationAttribute.GetValidationResult(value, validationContext);
                        if (validationResult != DataAnnotations.ValidationResult.Success)
                        {
                            validationResults.Add(new ChangeSetItemValidationResult()
                            {
                                Id = validationAttribute.GetType().FullName,
                                Message = validationResult.ErrorMessage,
                                Severity = EventLevel.Error,
                                Target = resource,
                                PropertyName = property.Name
                            });
                        }
                    }
                }
            }

            return Task.WhenAll();
        }
        /// <inheritdoc/>
        public Task ValidateEntityAsync(
            SubmitContext context,
            ChangeSetEntry entry,
            ValidationResults validationResults,
            CancellationToken cancellationToken)
        {
            Ensure.NotNull(validationResults, "validationResults");
            DataModificationEntry dataModificationEntry = entry as DataModificationEntry;
            if (dataModificationEntry != null)
            {
                object entity = dataModificationEntry.Entity;

                // TODO GitHubIssue#50 : should this PropertyDescriptorCollection be cached?
                PropertyDescriptorCollection properties =
                    new DataAnnotations.AssociatedMetadataTypeTypeDescriptionProvider(entity.GetType())
                    .GetTypeDescriptor(entity).GetProperties();

                DataAnnotations.ValidationContext validationContext = new DataAnnotations.ValidationContext(entity);

                foreach (PropertyDescriptor property in properties)
                {
                    validationContext.MemberName = property.Name;

                    IEnumerable<DataAnnotations.ValidationAttribute> validationAttributes =
                        property.Attributes.OfType<DataAnnotations.ValidationAttribute>();
                    foreach (DataAnnotations.ValidationAttribute validationAttribute in validationAttributes)
                    {
                        object value = property.GetValue(entity);
                        DataAnnotations.ValidationResult validationResult =
                            validationAttribute.GetValidationResult(value, validationContext);
                        if (validationResult != DataAnnotations.ValidationResult.Success)
                        {
                            validationResults.Add(new ValidationResult()
                            {
                                Id = validationAttribute.GetType().FullName,
                                Message = validationResult.ErrorMessage,
                                Severity = ValidationSeverity.Error,
                                Target = entity,
                                PropertyName = property.Name
                            });
                        }
                    }
                }
            }

            return Task.WhenAll();
        }
Пример #13
0
        public static ICustomTypeDescriptor Get(Type type)
        {
            try
            {
                locker.EnterReadLock();
                var metadataType = hashtable[type] as Type;
                ICustomTypeDescriptor descriptor = null;
                if (metadataType != null)
                {
                    descriptor = new AssociatedMetadataTypeTypeDescriptionProvider(type, metadataType).GetTypeDescriptor(type);
                }

                return descriptor;
            }
            finally
            {
                locker.ExitReadLock();
            }
        }
Пример #14
0
 private static void RegisterProvider(Type itemType, Type metadataType)
 {
     var association = new AssociatedMetadataTypeTypeDescriptionProvider(itemType, metadataType);
     TypeDescriptor.AddProviderTransparent(association, itemType);
 }
Пример #15
0
		static ICustomTypeDescriptor GetTypeDescriptor(object model, Type modelType) 
        {
            var provider = new AssociatedMetadataTypeTypeDescriptionProvider(modelType);
            return provider.GetTypeDescriptor(modelType, model);
        }
Пример #16
0
 /// <summary>
 /// Validates the specified validation context.
 /// </summary>
 /// <param name="validationContext">The validation context.</param>
 /// <param name="metadata">The metadata.</param>
 /// <returns></returns>
 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext, ModelMetadata metadata)
 {
     if (!IsValidInput()) {
         yield return new ValidationResult(string.Format("Value of the {0} field couldn´t be recognized as a valid page ", metadata.DisplayName));
     } else if (metadata.IsRequired && !IsValidPage()) {
         var customTypeDescriptor = new AssociatedMetadataTypeTypeDescriptionProvider(metadata.ContainerType).GetTypeDescriptor(metadata.ContainerType);
         if (customTypeDescriptor != null) {
             var descriptor = customTypeDescriptor.GetProperties().Find(metadata.PropertyName, true);
             var req = (new List<Attribute>(descriptor.Attributes.OfType<Attribute>())).OfType<RequiredAttribute>().FirstOrDefault();
             if (req != null) yield return new ValidationResult(req.FormatErrorMessage(metadata.DisplayName));
         }
     }
 }
        private static List<IDataAnnotationsValidatorAdapter> GetAdapters(Type type)
        {
            var typeDescriptor =
                new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);

            var adapters =
                GetAdapters(null, type, typeDescriptor.GetAttributes().OfType<ValidationAttribute>());

            var propertyDescriptors =
                typeDescriptor.GetProperties();

            foreach (PropertyDescriptor property in propertyDescriptors)
            {
                adapters.AddRange(GetAdapters(property, property.PropertyType, property.Attributes.OfType<ValidationAttribute>()));
            }

            return adapters;
        }
Пример #18
0
        public ParameterHandler(ParameterInfo parameterInfo)
        {
            if (IsSimpleType(parameterInfo.ParameterType) || IsEnumerable(parameterInfo.ParameterType))
            {
                GetRouteValues =
                    new ReadOnlyCollection<RouteValueHandler>(new List<RouteValueHandler>()
                    {
                        new RouteValueHandler(parameterInfo.Name, v => v)
                    });
            }
            else
            {
                var type = parameterInfo.ParameterType;
                var typeDesc = new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
                var propDescs = typeDesc.GetProperties();
                GetRouteValues = propDescs.OfType<PropertyDescriptor>()
                    .Select(desc => new RouteValueHandler(desc.Name, desc.GetValue)).ToList();
            }

            IsFromUri = true;
        }
Пример #19
0
 public IEnumerable<PropertyDescriptor> GetProperties(ModelBindingContext context)
 {
     var propertyCollection = new AssociatedMetadataTypeTypeDescriptionProvider(typeof(UserInfo)).GetTypeDescriptor(typeof(UserInfo)).GetProperties();
     var result = from PropertyDescriptor propDesc in propertyCollection where CanUpdateProperty(propDesc, context.PropertyFilter) select propDesc;
     return result;
 }
		public void Constructors_Null_AssociatedMetadataType_2 ()
		{
			var v = new AssociatedMetadataTypeTypeDescriptionProvider (typeof (string), null);
		}
		public void Constructors_Null_Type ()
		{
			var v = new AssociatedMetadataTypeTypeDescriptionProvider (null);
		}