/// <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); }
private TypeInformation CreateTypeInformation(Type type) { TypeInformation info = new TypeInformation(); ICustomTypeDescriptor typeDescriptor = new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type); info.TypeDescriptor = typeDescriptor; info.Prototype = CreateMetadataPrototype(AsAttributes(typeDescriptor.GetAttributes()), containerType: null, modelType: type, propertyName: null); Dictionary <string, PropertyInformation> properties = new Dictionary <string, PropertyInformation>(); foreach (PropertyDescriptor property in typeDescriptor.GetProperties()) { // Avoid re-generating a property descriptor if one has already been generated for the property name if (!properties.ContainsKey(property.Name)) { if (property.Attributes.OfType <IUnvalidatable>().Any()) { continue; } properties.Add(property.Name, CreatePropertyInformation(type, property)); } } info.Properties = properties; return(info); }
private object BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { Type modelType = bindingContext.ModelType; //绑定字典 if (this.Match(modelType, typeof(IDictionary <,>))) { return(this.BindDictionary(controllerContext, bindingContext)); } //绑定集合 if (this.Match(modelType, typeof(IEnumerable <>))) { return(this.BindCollection(controllerContext, bindingContext)); } 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); }
private static IList <Attribute> GetModelMetadataAttributes(ModelMetadata metadata) { var customTypeDescriptor = new AssociatedMetadataTypeTypeDescriptionProvider(metadata.ContainerType).GetTypeDescriptor(metadata.ContainerType); if (customTypeDescriptor != null) { var descriptor = customTypeDescriptor.GetProperties().Find(metadata.PropertyName, true); return((new List <Attribute>(descriptor.Attributes.OfType <Attribute>())).ToList <Attribute>()); } return(null); }
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); }
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); }
/// <summary> /// 获取主键值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> private static BsonValue GetKeyValue <T>(T obj) { var type = typeof(T); var descriptor = new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type); if (descriptor == null) { return(null); } object id = null; foreach (PropertyDescriptor propertyDescriptor in descriptor.GetProperties()) { var key = propertyDescriptor.Name; if (string.Equals(key, "id", StringComparison.OrdinalIgnoreCase)) { id = propertyDescriptor.GetValue(obj); break; } var b = false; foreach (Attribute validationAttribute in propertyDescriptor.Attributes) { if (!(validationAttribute is KeyAttribute)) { continue; } b = true; break; } if (!b) { continue; } id = propertyDescriptor.GetValue(obj); break; } return(id == null ? null : new BsonValue(id)); }
private static string GetErrorMessageForDataTypeAttribute(ModelMetadata metadata) { string retVal = null; 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 <DataTypeAttribute>().FirstOrDefault(); if (req != null) { retVal = (string)req.ErrorMessageResourceType?.GetProperty(req.ErrorMessageResourceName)?.GetMethod.Invoke(null, null); } } return(retVal); }
private static string GetErrorMessage(ModelMetadata metadata) { string retVal = String.Empty; 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) { retVal = req.ErrorMessage; } } return(retVal); }
/// <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))); } }
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; }
private object BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { Type modelType = bindingContext.ModelType; //绑定字典 if (this.Match(modelType, typeof(IDictionary <,>))) { return(this.BindDictionary(controllerContext, bindingContext)); } //绑定集合 if (this.Match(modelType, typeof(IEnumerable <>))) { return(this.BindCollection(controllerContext, bindingContext)); } 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); } ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, modelType); MyCompositeModelValidator validator = new MyCompositeModelValidator(metadata, controllerContext); foreach (ModelValidationResult result in validator.Validate(null)) { string key = (bindingContext.ModelName ?? "") + "." + (result.MemberName ?? ""); key = key.Trim('.'); controllerContext.Controller.ViewData.ModelState.AddModelError(key, result.Message); } return(model); }
public static string GetPropertyDisplayName(this ValidationContext validationContext, string propertyName) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } if (propertyName == null) { throw new ArgumentNullException(nameof(propertyName)); } if (string.IsNullOrWhiteSpace(propertyName)) { throw new ArgumentException("Value cannot be empty or whitespace only string.", nameof(propertyName)); } var typeDescriptor = new AssociatedMetadataTypeTypeDescriptionProvider(validationContext.ObjectType).GetTypeDescriptor(validationContext.ObjectType); var property = typeDescriptor.GetProperties().Find(propertyName, true); if (property == null) { throw new ArgumentException("Property not found", nameof(propertyName)); } IEnumerable <Attribute> attributes = property.Attributes.Cast <Attribute>(); DisplayAttribute display = attributes.OfType <DisplayAttribute>().FirstOrDefault(); if (display != null) { return(display.GetName()); } var displayName = attributes.OfType <DisplayNameAttribute>().FirstOrDefault(); if (displayName != null) { return(displayName.DisplayName); } return(propertyName); }