//public static bool Validate<T>(this T obj, string keySufix, Dictionary<string, string> result) //{ // try // { // ValidationResults summary = Validation.Validate<T>(obj); // if (summary != null && summary.Count > 0) // { // foreach (var item in summary) // { // string key = string.Empty; // if (!string.IsNullOrEmpty(item.Tag)) // key = keySufix + item.Tag; // else // key = keySufix + item.Key; // if (!result.Keys.Contains(key)) // result.Add(key, item.Message); // } // return false; // } // return true; // } // catch (Exception ex) // { // result.Add("Exception", ex.Message); // return false; // } //} /// <summary>Check the added data annotations and Validate model</summary> public static bool ValidateModel(this object obj, ref Dictionary <string, string> listErrors) { // get the name of the buddy class for obj MetadataTypeAttribute metadataAttrib = obj.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault() as MetadataTypeAttribute; // if metadataAttrib is null, then obj doesn't have a buddy class, and in such a case, we'll work with the model class Type buddyClassOrModelClass = metadataAttrib != null ? metadataAttrib.MetadataClassType : obj.GetType(); var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass).Cast <PropertyDescriptor>(); var modelClassProperties = TypeDescriptor.GetProperties(obj.GetType()).Cast <PropertyDescriptor>(); var errors = from modelProp in modelClassProperties from attribute in modelProp.Attributes.OfType <ValidationAttribute>() // get only the attributes of type ValidationAttribute where !attribute.IsValid(modelProp.GetValue(obj)) select new KeyValuePair <string, string>(modelProp.Name, attribute.FormatErrorMessage(string.Empty)); if (errors != null && errors.Count() > 0) { foreach (var item in errors) { if (listErrors.ContainsKey(item.Key)) { listErrors[item.Key] = string.Format("{0}. {1}", listErrors[item.Key], item.Value); } else { listErrors.Add(item.Key, item.Value); } } return(false); } return(true); }
public static string GetDisplayName <TModel, TProperty>(this TModel model, Expression <Func <TModel, TProperty> > expression) { Type type = typeof(TModel); MemberExpression memberExpression = (MemberExpression)expression.Body; string propertyName = ((memberExpression.Member is PropertyInfo || !string.IsNullOrEmpty(memberExpression.Member.Name)) ? memberExpression.Member.Name : null); // First look into attributes on a type and it's parents var p = type.GetProperty(propertyName) ?? type.GetProperty(propertyName, BindingFlags.Static); var attr = (DisplayAttribute)p.GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); // Look for [MetadataType] attribute in type hierarchy // http://stackoverflow.com/questions/1910532/attribute-isdefined-doesnt-see-attributes-applied-with-metadatatype-class if (attr == null) { MetadataTypeAttribute metadataType = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); if (metadataType != null) { var property = metadataType.MetadataClassType.GetProperty(propertyName); if (property != null) { attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault(); } } } return((attr != null) ? attr.Name : String.Empty); }
static void Main(string[] args) { MetadataTypeAttribute[] metadataTypes = typeof(MyTestClass).GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType <MetadataTypeAttribute>().ToArray(); MetadataTypeAttribute metadata = metadataTypes.FirstOrDefault(); if (metadata != null) { PropertyInfo[] properties = metadata.MetadataClassType.GetProperties(); foreach (PropertyInfo propertyInfo in properties) { Console.WriteLine(Attribute.IsDefined(propertyInfo, typeof(MyAttribute))); Console.WriteLine(propertyInfo.IsDefined(typeof(MyAttribute), true)); Console.WriteLine(propertyInfo.GetCustomAttributes(true).Length); RequiredAttribute attrib = (RequiredAttribute)propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), true)[0]; Console.WriteLine(attrib.ErrorMessage); } // Results: // True // True // 2 // MyField is Required } Console.ReadLine(); }
// string DisplayName = UtilHelper.GetDisplayName<CustomerModel>(m => m.FinancialCardNum); public static string GetDisplayName <TModel>(Expression <Func <TModel, object> > expression) { Type type = typeof(TModel); string propertyName = null; string[] properties = null; IEnumerable <string> propertyList; //unless it's a root property the expression NodeType will always be Convert switch (expression.Body.NodeType) { case ExpressionType.Convert: case ExpressionType.ConvertChecked: var ue = expression.Body as UnaryExpression; propertyList = (ue != null ? ue.Operand : null).ToString().Split(".".ToCharArray()).Skip(1); //don't use the root property break; default: propertyList = expression.Body.ToString().Split(".".ToCharArray()).Skip(1); break; } //the propert name is what we're after propertyName = propertyList.Last(); //list of properties - the last property name properties = propertyList.Take(propertyList.Count() - 1).ToArray(); //grab all the parent properties Expression expr = null; foreach (string property in properties) { PropertyInfo propertyInfo = type.GetProperty(property); expr = Expression.Property(expr, type.GetProperty(property)); type = propertyInfo.PropertyType; } DisplayAttribute attr; attr = (DisplayAttribute)type.GetProperty(propertyName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); // Look for [MetadataType] attribute in type hierarchy // http://stackoverflow.com/questions/1910532/attribute-isdefined-doesnt-see-attributes-applied-with-metadatatype-class if (attr == null) { MetadataTypeAttribute metadataType = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); if (metadataType != null) { var property = metadataType.MetadataClassType.GetProperty(propertyName); if (property != null) { attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault(); } } } //To support translations call attr.GetName() instead of attr.Name return((attr != null) ? attr.GetName() : propertyName); //return (attr != null) ? attr.GetName() : String.Empty; }
public string this[string columnName] { get { List <ValidationAttribute> validationAttributes = new List <ValidationAttribute>(); MetadataTypeAttribute metadataType = this.GetType().GetCustomAttributes(true).OfType <MetadataTypeAttribute>().FirstOrDefault(); if (metadataType != null) { PropertyInfo p = metadataType.MetadataClassType.GetProperty(columnName); if (p != null) { validationAttributes = p.GetCustomAttributes(true).OfType <ValidationAttribute>().ToList(); } } PropertyInfo currentProperty = this.GetType().GetProperty(columnName); validationAttributes.AddRange(currentProperty.GetCustomAttributes(true).OfType <ValidationAttribute>().ToList()); foreach (ValidationAttribute currentAttribute in validationAttributes) { try { currentAttribute.Validate(currentProperty.GetValue(this, null), columnName); } catch (Exception ex) { return(ex.Message); } } return(string.Empty); } }
private void GetValidationsForDto(GetValidationsParms parms) { parms.JsonString.Append(parms.JsonObjectName + ": { "); var dtoClass = TypeHelper.GetObjectType(parms.DtoObjectName, false, parms.DtoAlternateNamespace, parms.DtoAssemblyNames.ToArray()); if (dtoClass == null) { var message = string.Format("DTO '{0}' not found.", parms.DtoObjectName); throw new Exception(message); } var properties = dtoClass.GetProperties(); if (properties != null) { var isFirstProp = true; DealWithProperties(properties, ref parms, ref isFirstProp); MetadataTypeAttribute[] metadataTypes = dtoClass.GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType <MetadataTypeAttribute>().ToArray(); MetadataTypeAttribute metadata = metadataTypes.FirstOrDefault(); if (metadata != null) { properties = metadata.MetadataClassType.GetProperties(); if (properties != null) { DealWithProperties(properties, ref parms, ref isFirstProp); } } } parms.JsonString.Append("}"); }
private void CachedValidationAttribute(Type type) { if (!ObjectValidaterFactory._type.ContainsKey(this.TypeName)) { PropertyInfo[] modelProperties = type.GetProperties(); MetadataTypeAttribute metaAttribute = Attribute.GetCustomAttribute(type, typeof(MetadataTypeAttribute)) as MetadataTypeAttribute; if (metaAttribute != null) { Type metadataType = metaAttribute.MetadataClassType; modelProperties = metadataType.GetProperties(); } Type typeValidationAttribute = typeof(ValidationAttribute); int count = 0; PropertyInfo[] array2 = modelProperties; for (int i = 0; i < array2.Length; i++) { PropertyInfo pro = array2[i]; string key = string.Format(ObjectValidaterFactory._proFormat, this.TypeName, pro.Name); Attribute[] array = Attribute.GetCustomAttributes(pro, typeValidationAttribute); count += array.Length; ObjectValidaterFactory._proValidation[key] = array; } ObjectValidaterFactory._type[this.TypeName] = (count > 0); } }
public TableEntrySelected(LocalizationTable table, long id, Locale locale, MetadataType supportedType) { m_Table = table; m_Locale = locale; m_KeyId = id; m_MetadataType = new MetadataTypeAttribute(supportedType); }
public static Type GetAssociatedMetadataType(Type type) { Type associatedMetadataType = null; lock (_metadataTypeCache) { if (_metadataTypeCache.TryGetValue(type, out associatedMetadataType)) { return(associatedMetadataType); } } // Try association attribute MetadataTypeAttribute attribute = (MetadataTypeAttribute)Attribute.GetCustomAttribute(type, typeof(MetadataTypeAttribute)); if (attribute != null) { associatedMetadataType = attribute.MetadataClassType; } lock (_metadataTypeCache) { _metadataTypeCache[type] = associatedMetadataType; } return(associatedMetadataType); }
/// <summary> /// Verifies that the <see cref="MetadataTypeAttribute"/> reference does not contain a cyclic reference and /// registers the AssociatedMetadataTypeTypeDescriptionProvider in that case. /// </summary> /// <param name="type">The entity type with the MetadataType attribute.</param> private static void RegisterAssociatedMetadataTypeTypeDescriptor(Type type) { Type currentType = type; HashSet <Type> metadataTypeReferences = new HashSet <Type>(); metadataTypeReferences.Add(currentType); while (true) { MetadataTypeAttribute attribute = (MetadataTypeAttribute)Attribute.GetCustomAttribute(currentType, typeof(MetadataTypeAttribute)); if (attribute == null) { break; } else { currentType = attribute.MetadataClassType; // If we find a cyclic reference, throw an error. if (metadataTypeReferences.Contains(currentType)) { throw Error.InvalidOperation(Resource.CyclicMetadataTypeAttributesFound, type.FullName); } else { metadataTypeReferences.Add(currentType); } } } // If the MetadataType reference chain doesn't contain a cycle, register the use of the AssociatedMetadataTypeTypeDescriptionProvider. RegisterCustomTypeDescriptor(new AssociatedMetadataTypeTypeDescriptionProvider(type), type); }
/// <summary> /// Gets the validators. /// </summary> /// <param name="modelType">Type of the model.</param> /// <param name="propertyName">Name of the property.</param> /// <returns></returns> public IEnumerable <ValidationAttribute> GetValidators(Type modelType, string propertyName) { if (modelType == null) { throw new ArgumentNullException("modelType"); } if (String.IsNullOrEmpty(propertyName)) { throw new ArgumentException("Value cannot be null or empty.", "propertyName"); } // check for a validation "buddy type" MetadataTypeAttribute metadataTypeAttribute = TypeDescriptor.GetAttributes(modelType).OfType <MetadataTypeAttribute>().SingleOrDefault(); if (metadataTypeAttribute != null) { modelType = metadataTypeAttribute.MetadataClassType; } return(from property in GetProperties(modelType) where property.Name == propertyName from attribute in GetAttributes(property) select attribute); }
// 根据成员表达式,获取模型指定Property的DisplayName属性 string GetDisplayName <TValue>(Expression <Func <TModel, TValue> > expression) { Type type = typeof(TModel); MemberExpression memberExpression = (MemberExpression)expression.Body; string propertyName = ((memberExpression.Member is PropertyInfo) ? memberExpression.Member.Name : null); // First look into attributes on a type and it's parents DisplayNameAttribute attr; attr = (DisplayNameAttribute)type.GetProperty(propertyName).GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault(); // Look for [MetadataType] attribute in type hierarchy // http://stackoverflow.com/questions/1910532/attribute-isdefined-doesnt-see-attributes-applied-with-metadatatype-class if (attr == null) { MetadataTypeAttribute metadataType = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); if (metadataType != null) { var property = metadataType.MetadataClassType.GetProperty(propertyName); if (property != null) { attr = (DisplayNameAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault(); } } } return((attr != null) ? attr.DisplayName : propertyName); // String.Empty; }
/// <summary> /// Gets the property Display Name. /// </summary> /// <param name="pInfo">The p info.</param> /// <returns></returns> public static string GetDisplayName(PropertyInfo pInfo, Type metaDataType) { if (null == pInfo) { return(String.Empty); } string propertyName = pInfo.Name; DisplayAttribute attr = (DisplayAttribute)metaDataType.GetProperty(propertyName) .GetCustomAttributes(typeof(DisplayAttribute), true) .SingleOrDefault(); if (attr == null) { MetadataTypeAttribute otherType = (MetadataTypeAttribute)metaDataType.GetCustomAttributes(typeof(MetadataTypeAttribute), true) .FirstOrDefault(); if (otherType != null) { var property = otherType.MetadataClassType.GetProperty(propertyName); if (property != null) { attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault(); } } } return((attr != null) ? attr.Name : String.Empty); }
public static string GetDisplayName <TModel, TProperty>(this TModel model, Expression <Func <TModel, TProperty> > expression) { Type type = typeof(TModel); MemberExpression memberExpression = (MemberExpression)expression.Body; string propertyName = ((memberExpression.Member is PropertyInfo) ? memberExpression.Member.Name : null); DisplayAttribute attr; attr = (DisplayAttribute)type.GetProperty(propertyName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); if (attr == null) { MetadataTypeAttribute metadataType = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); if (metadataType != null) { var property = metadataType.MetadataClassType.GetProperty(propertyName); if (property != null) { attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault(); } } } return((attr != null) ? attr.Name : String.Empty); }
private List <ColumnTitle> GetColumnTitle(Type entityType, params string[] notExportCol) { var coltitle = new List <ColumnTitle>(); var Properties = entityType.GetProperties().Where(p => p.SetMethod.Attributes == (MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName)).ToList(); foreach (var prop in Properties) { if (!notExportCol.Any(p => p == prop.Name)) { var attr = (DisplayAttribute)entityType.GetProperty(prop.Name).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); if (attr == null) { MetadataTypeAttribute metadataType = (MetadataTypeAttribute)entityType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); if (metadataType != null) { var property = metadataType.MetadataClassType.GetProperty(prop.Name); if (property != null) { attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); } } } var column = new ColumnTitle(); if (attr == null) { column = new ColumnTitle() { Name = prop.Name, DisplayName = prop.Name }; coltitle.Add(column); } else if (!notExportCol.Any(p => p == attr.Name)) { column = new ColumnTitle() { Name = prop.Name, DisplayName = attr.GetName(), ShortName = attr.GetShortName(), Description = attr.GetDescription(), GroupName = attr.GetGroupName(), Prompt = attr.GetPrompt(), Order = attr.GetOrder() }; coltitle.Add(column); } } } if (coltitle.Any(p => p.Order == null)) { return(coltitle); } else { return(coltitle.OrderBy(p => p.Order).ToList()); } }
public void Constructor_NullValue() { MetadataTypeAttribute attribute = new MetadataTypeAttribute(null); ExceptionHelper.ExpectInvalidOperationException(() => { Type classType = attribute.MetadataClassType; }, Resources.DataAnnotationsResources.MetadataTypeAttribute_TypeCannotBeNull); }
public object Clone(object obj) { Type type = obj.GetType(); MetadataTypeAttribute metadataTypeAttribute = ((MetadataTypeAttribute[])type.GetCustomAttributes(typeof(MetadataTypeAttribute), true)) .FirstOrDefault(); if (metadataTypeAttribute == null) { throw new ArgumentException("obj must have MetadataTypeAttribute applied to it"); } Type metaType = metadataTypeAttribute.MetadataClassType; ConstructorInfo metaConstructor = metaType.GetConstructor(new Type[0]); if (metaConstructor == null) { throw new ArgumentException("obj metadata type must have a parameterless constructor"); } object meta = metaConstructor.Invoke(new object[0]); var metaProps = metaType.GetProperties( BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.Instance); var props = type.GetProperties( BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.Instance); foreach (PropertyInfo p in metaProps.Where(p => p.CanRead && p.CanWrite)) { string propertyName = p.Name; PropertyInfo objProperty = props.First(pr => pr.Name == propertyName); object objValue = objProperty.GetValue(obj, null); if (p.PropertyType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection <>)) && !typeof(Array).IsAssignableFrom(p.PropertyType)) { if (objValue != null) { ConstructorInfo pConstructor = p.PropertyType.GetConstructor(new Type[0]); if (pConstructor != null) { object collection = pConstructor.Invoke(new object[0]); MethodInfo addMethod = p.PropertyType.GetMethod("Add"); foreach (object o in (IEnumerable)objValue) { addMethod.Invoke(collection, new[] { o }); } p.SetValue(meta, collection, null); } } } else { p.SetValue(meta, objValue, null); } } return(meta); }
protected override ICustomTypeDescriptor GetTypeDescriptor(Type type) { MetadataTypeAttribute metadata = type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType <MetadataTypeAttribute>().FirstOrDefault(); if (metadata != null) { return((new AssociatedMetadataTypeTypeDescriptionProvider(type, metadata.MetadataClassType)).GetTypeDescriptor(type)); } return(base.GetTypeDescriptor(type)); }
public static string DisplayNameFor <T>(Expression <Func <T, object> > expression) { string propertyName = String.Empty; PropertyInfo propInfo = null; Type type = null; MemberExpression memberExpression = expression.Body as MemberExpression ?? ((UnaryExpression)expression.Body).Operand as MemberExpression; if (memberExpression != null) { propertyName = memberExpression.Member.Name; type = memberExpression.Member.DeclaringType; propInfo = type.GetProperty(propertyName); } if (!String.IsNullOrEmpty(propertyName) && type != null) { DisplayAttribute attribute1 = propInfo.GetCustomAttributes(typeof(DisplayAttribute), true).FirstOrDefault() as DisplayAttribute; if (attribute1 != null) { return(attribute1.Name); } DisplayNameAttribute attribute2 = propInfo.GetCustomAttributes(typeof(DisplayNameAttribute), true).FirstOrDefault() as DisplayNameAttribute; if (attribute2 != null) { return(attribute2.DisplayName); } MetadataTypeAttribute metadataType = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); if (metadataType != null) { PropertyInfo metaProp = metadataType.MetadataClassType.GetProperty(propInfo.Name); if (metaProp != null) { DisplayAttribute attribute3 = (DisplayAttribute)metaProp.GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); if (attribute3 != null) { return(attribute3.Name); } DisplayNameAttribute attribute4 = (DisplayNameAttribute)metaProp.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault(); if (attribute4 != null) { return(attribute4.DisplayName); } } } } return(String.Empty); }
private PropertyInfo[] ObterPropriedadesDoModel(object modelComAnotacoesRequired, ref object objetoMetaData) { MetadataTypeAttribute metaDataAttr = (MetadataTypeAttribute)modelComAnotacoesRequired.GetType().GetCustomAttributes(false).FirstOrDefault(a => a is MetadataTypeAttribute); if (metaDataAttr == null) // o model não possui uma classe MetaData associada, usar metadata do EDMX ou model { return(modelComAnotacoesRequired.GetType().GetProperties()); } // obtem propriedades da classe MetaData objetoMetaData = Activator.CreateInstance(metaDataAttr.MetadataClassType); return(objetoMetaData.GetType().GetProperties()); }
public TableEntrySelected(LocalizationTable table, long id, Locale locale, MetadataType supportedType) { m_Table = table; m_Locale = locale; m_KeyId = id; m_SharedMetadataType = new MetadataTypeAttribute(supportedType); // Remove the shared entry flag var entryFlags = supportedType & ~MetadataType.AllSharedTableEntries; m_MetadataType = new MetadataTypeAttribute(entryFlags); }
/// <summary> /// Generate attribute list of object /// </summary> /// <typeparam name="ATTR"></typeparam> /// <param name="t"></param> /// <returns></returns> public static Dictionary <string, ATTR> CreateAttributeDictionary <ATTR>(Type t) where ATTR : class { try { Dictionary <string, ATTR> dicAttr = new Dictionary <string, ATTR>(); if (t != null) { #region Get Attribute from Meta Data Object object[] mtAttr = t.GetCustomAttributes(typeof(MetadataTypeAttribute), true); if (mtAttr.Length > 0) { MetadataTypeAttribute metadata = mtAttr[0] as MetadataTypeAttribute; if (metadata.MetadataClassType != null) { foreach (PropertyInfo prop in metadata.MetadataClassType.GetProperties()) { object[] objAttr = prop.GetCustomAttributes(typeof(ATTR), true); if (objAttr.Length <= 0) { continue; } dicAttr.Add(prop.Name, objAttr[0] as ATTR); } } } #endregion #region Get Attribute from Object instance foreach (PropertyInfo prop in t.GetProperties()) { object[] objAttr = prop.GetCustomAttributes(typeof(ATTR), true); if (objAttr.Length <= 0) { continue; } dicAttr.Add(prop.Name, objAttr[0] as ATTR); } #endregion } return(dicAttr); } catch (Exception) { throw; } }
public static string GetDisplayName <TModel, TProperty>(this TModel model, Expression <Func <TModel, TProperty> > expression, string pushText = null) { Type type = typeof(TModel); MemberExpression memberExpression = (MemberExpression)expression.Body; string propertyName = ((memberExpression.Member is PropertyInfo) ? memberExpression.Member.Name : null); DisplayAttribute attr = (DisplayAttribute)type.GetProperty(propertyName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); if (attr == null) { MetadataTypeAttribute metadataType = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); if (metadataType != null) { var property = metadataType.MetadataClassType.GetProperty(propertyName); if (property != null) { attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); } } } var displayName = attr != null ? attr.Name : propertyName; return($"{pushText} {displayName} {pushText}".TrimStart().TrimEnd()); }
// Get [DysplayName] attribute of property // http://stackoverflow.com/questions/5474460/get-displayname-attribute-of-a-property-in-strongly-typed-way public static string DisplayName <TModel>(Expression <Func <TModel, object> > expression) { Type type = typeof(TModel); IEnumerable <string> properties; switch (expression.Body.NodeType) { case ExpressionType.Convert: case ExpressionType.ConvertChecked: var unary = expression.Body as UnaryExpression; properties = (unary != null ? unary.Operand : null).ToString().Split(".".ToCharArray()).Skip(1); break; default: properties = expression.Body.ToString().Split(".".ToCharArray()).Skip(1); break; } string property_name = properties.Last(); Expression subexpression = null; foreach (var property in properties.Take(properties.Count() - 1)) { PropertyInfo info = type.GetProperty(property); subexpression = Expression.Property(subexpression, type.GetProperty(property)); type = info.PropertyType; } DisplayAttribute attribute = (DisplayAttribute)type.GetProperty(property_name).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); // Look for [MetadataType] attribute in type hierarchy // http://stackoverflow.com/questions/1910532/attribute-isdefined-doesnt-see-attributes-applied-with-metadatatype-class if (attribute == null) { MetadataTypeAttribute metadata_type = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); if (metadata_type != null) { var property = metadata_type.MetadataClassType.GetProperty(property_name); if (property != null) { attribute = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault(); } } } return((attribute != null) ? attribute.GetName() : string.Empty); }
/// <summary> /// 注册类型元数据描述类 /// 常用于使用 System.ComponentModel.DataAnnotations.Validator 进行数据验证时批量注入 MetadataTypes /// </summary> public static void Register(Assembly assembly) { foreach (Type type in assembly.GetTypes()) { AttributeCollection collection = TypeDescriptor.GetAttributes(type); foreach (var attr in collection) { MetadataTypeAttribute m = attr as MetadataTypeAttribute; if (m != null) { TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(type, m.MetadataClassType), type); } } } }
private static MemberInfo GetMatchingElement(MemberInfo element) { Type sourceType = element as Type; bool elementIsType = sourceType != null; if (sourceType == null) { sourceType = element.DeclaringType; } #if !(NETSTANDARD2_0 || NETCOREAPP2_1) MetadataTypeAttribute metadataTypeAttribute = (MetadataTypeAttribute) Attribute.GetCustomAttribute(sourceType, typeof(MetadataTypeAttribute), false); if (metadataTypeAttribute == null) { return(element); } sourceType = metadataTypeAttribute.MetadataClassType; if (elementIsType) { return(sourceType); } #endif MemberInfo[] matchingMembers = sourceType.GetMember( element.Name, element.MemberType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (matchingMembers.Length > 0) { MethodBase methodBase = element as MethodBase; if (methodBase == null) { return(matchingMembers[0]); } Type[] parameterTypes = methodBase.GetParameters().Select(pi => pi.ParameterType).ToArray(); return(matchingMembers.Cast <MethodBase>().FirstOrDefault(mb => MatchMethodBase(mb, parameterTypes)) ?? element); } return(element); }
private void AddDisplayName(object objectToValidate, string name) { MetadataTypeAttribute metadataTypeAttribute = (objectToValidate.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), false).FirstOrDefault() as MetadataTypeAttribute); if (metadataTypeAttribute != null) { PropertyInfo pi1 = metadataTypeAttribute.MetadataClassType.GetProperties().Where(p => p.Name == name).FirstOrDefault(); if (pi1 != null) { DisplayNameAttribute da = pi1.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault() as DisplayNameAttribute; if (da != null) { this._displayFields.Add(da.DisplayName); } } } }
public static Type GetAssociatedMetadataType(Type type) { Type type2 = null; if (AssociatedMetadataTypeTypeDescriptor.TypeDescriptorCache._metadataTypeCache.TryGetValue(type, out type2)) { return(type2); } MetadataTypeAttribute metadataTypeAttribute = (MetadataTypeAttribute)Attribute.GetCustomAttribute(type, typeof(MetadataTypeAttribute)); if (metadataTypeAttribute != null) { type2 = metadataTypeAttribute.MetadataClassType; } AssociatedMetadataTypeTypeDescriptor.TypeDescriptorCache._metadataTypeCache.TryAdd(type, type2); return(type2); }
/// <summary> /// Return a list of broken business rules (data annotations) /// </summary> /// <returns></returns> public ICollection<ValidationResult> BrokenRules<TModel>(TModel model) { // Need to add data annotations of the associated metadataclass // Check to see if we have a meta data tag for this class (This should be cached?) MetadataTypeAttribute metadataTypeAttribute = (MetadataTypeAttribute)Attribute.GetCustomAttribute(typeof(TModel), typeof(MetadataTypeAttribute)); if (metadataTypeAttribute != null) { // Add the meta data class so we get the additional data annotations System.ComponentModel.TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(TModel), metadataTypeAttribute.MetadataClassType.UnderlyingSystemType), typeof(TModel)); } ValidationContext validationContext = new ValidationContext(model, null, null); List<ValidationResult> validationResults = new List<ValidationResult>(); Validator.TryValidateObject(model, validationContext, validationResults, true); return validationResults; } // BrokenRules
public void PrintProperties(object vehiculo) { Type type = vehiculo.GetType(); Console.WriteLine(string.Format("Caracteristicas del vehiculo {0}:", type.Name)); //Obtenemos tipo de la clase PropertyInfo[] propertyInfos = type.GetProperties(); PropertyInfo[] propertyMetadataInfos = null; //Miramos si la clase tienen metadatas var metadataTypes = (MetadataTypeAttribute[])type.GetCustomAttributes(typeof(MetadataTypeAttribute), true); MetadataTypeAttribute metadata = metadataTypes.FirstOrDefault(); ///Si la clase tiene Metadatos if (metadata != null) { propertyMetadataInfos = metadata.MetadataClassType.GetProperties(); } foreach (PropertyInfo propertyInfo in propertyInfos) { if (propertyMetadataInfos != null && propertyMetadataInfos.Count(p => p.Name == propertyInfo.Name) > 0) { PropertyInfo propertyMetadataInfo = metadata.MetadataClassType.GetProperty(propertyInfo.Name); if (propertyMetadataInfo.IsDefined(typeof(ElementAssociatedAttribute), true)) { var attribute = (ElementAssociatedAttribute)propertyMetadataInfo.GetCustomAttributes(typeof(ElementAssociatedAttribute), true)[0]; if (attribute != null) { Console.WriteLine("La propiedad {0}, de valor {1}, se guarda en {2}.", propertyInfo.Name, propertyInfo.GetValue(vehiculo), attribute.OtherTable); } } } else { Console.WriteLine("La propiedad {0}, de valor {1}, se guarda en {2}.", propertyInfo.Name, propertyInfo.GetValue(vehiculo), "su tabla normal"); } } }