/// <summary> /// Gets all of the properties for a type, filtering out properties with duplicate names by choosing the property with /// the most derived declaring type. /// </summary> /// <param name="type">Type to get properties for</param> /// <param name="bindingFlags">Binding flags for properties</param> /// <param name="predicate">Any additional filtering on properties</param> /// <returns>Filtered properties</returns> private static IEnumerable <PropertyInfo> GetPropertiesWithoutDuplicateNames(IReflect type, BindingFlags bindingFlags, Func <PropertyInfo, bool> predicate = null) { IList <MemberInfo> properties = predicate != null ? type.GetProperties(bindingFlags) .Where(predicate) .Cast <MemberInfo>() .ToList() : type.GetProperties(bindingFlags) .Cast <MemberInfo>() .ToList(); return(GetMembersWithoutDuplicateNames(properties) .Cast <PropertyInfo>()); }
private static Dictionary <MemberInfo, object> GetMembers(IReflect type, object obj) { var members = new Dictionary <MemberInfo, object>(); const BindingFlags bindingFlagsAll = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; var fields = type.GetFields(bindingFlagsAll); foreach (var field in fields) { members.Add(field, field.GetValue(obj)); } var properties = type.GetProperties(bindingFlagsAll); foreach (var property in properties) { var backingField = property.GetBackingField(); if (backingField != null) { members.Remove(backingField); members.Add(property, property.GetValue(obj, null)); } } return(members); }
public bool ContainsValidToken(string value, IReflect type) { if (value == null) { return(false); } if (type.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance).Any(t => Regex.Match(value, $@"({{[L,U]?{{)(\[\d+\])?({t.Name})(\[\d+\])?(\..*)?(\[\d+\])?({{.}})?({{\d}})?(\[\d+\])?(}}}})").Success)) { return(true); } if (!ContainsTokenSyntax(value)) { return(false); } var token = GetTokens(value); if (token.Count == 0) { return(false); } foreach (var item in ReplacementDictionary) { for (var i = 0; i < token.Count; i++) { if (item.Key == token[i].Value) { return(true); } } } return(false); }
internal Accessor(IReflect type, bool ignoreCase, bool includeNonPublic) { Type = type; IgnoreCase = ignoreCase; IncludesNonPublic = includeNonPublic; Comparer = IgnoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; var flags = BindingFlags.Public | BindingFlags.Instance; if (IncludesNonPublic) { flags = flags | BindingFlags.NonPublic; } Properties = Type.GetProperties(flags); _objectGettersCache = new Dictionary <string, Func <object, object> >(Properties.Length, Comparer); _objectSettersCache = new Dictionary <string, Action <object, object> >(Properties.Length, Comparer); foreach (var prop in Properties) { var propName = prop.Name; _objectGettersCache[propName] = AccessorBuilder.BuildGetter(prop, IncludesNonPublic); _objectSettersCache[propName] = AccessorBuilder.BuildSetter(prop, IncludesNonPublic); } }
private void FillPropertiesRecursively(object instance, IReflect type, int index) { var propertyInfos = type .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Select(propertyInfo => new PropertyTargetInfo(propertyInfo)); var fieldInfos = type .GetFields(BindingFlags.Public | BindingFlags.Instance) .Select(fieldInfo => new FieldTargetInfo(fieldInfo)); var targetInfos = propertyInfos.Cast <TargetInfo>().Union(fieldInfos); foreach (var targetInfo in targetInfos) { if (targetInfo.IsNullable() && !Options.FillNullables) { continue; } var buildFunction = GetBuildFunction(targetInfo, index); if (buildFunction == null) { continue; } var propertyValue = buildFunction.Invoke(); targetInfo.SetValue(instance, propertyValue); if (CanApplyRecursion(targetInfo)) { FillPropertiesRecursively(propertyValue, targetInfo.TargetType, index); } } }
/// <summary> /// Gets the properties by attribute and relationship attributes where the referencing type is of the matching relationship entity. /// </summary> /// <param name="type">Type of the entity to lookup that properties of.</param> /// <param name="matchingRelationshipEntityLogicalName">Name of the matching relationship entity logical.</param> /// <param name="propertiesByAttribute">The properties by attribute.</param> /// <param name="relationshipProperties">The relationship properties.</param> public static void GetPropertiesByAttributeWithMatchingRelationships(IReflect type, string matchingRelationshipEntityLogicalName, out Dictionary <string, PropertyInfo> propertiesByAttribute, out List <string> relationshipProperties) { propertiesByAttribute = new Dictionary <string, PropertyInfo>(); relationshipProperties = new List <string>(); foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.Name != "Id")) { var att = property.GetCustomAttribute <AttributeLogicalNameAttribute>(); if (att == null || (property.PropertyType.IsGenericType && property.PropertyType.GenericTypeArguments[0].IsEnum && property.Name.EndsWith("Enum"))) { // No AttributeLogicalName parameter, or the property is for a nullable Enum continue; } var relationship = property.GetCustomAttribute <RelationshipSchemaNameAttribute>(); if (relationship == null) { propertiesByAttribute.Add(att.LogicalName, property); } else if (EntityHelper.GetEntityLogicalName(property.PropertyType) == matchingRelationshipEntityLogicalName) { relationshipProperties.Add(att.LogicalName); } } }
private void ResolveReference(IReflect instanceType, object instance) { var fields = instanceType.GetFields( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); var referencedFields = fields .Where(fieldInfo => Attribute.IsDefined(fieldInfo, typeof(ReferenceAttribute))); foreach (var info in referencedFields) { var referenceName = info.FieldType.Name; var referenceInstance = FindInstance(referenceName) ?? throw new Exception(); info.SetValue(instance, referenceInstance); } var properties = instanceType.GetProperties( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); var referencedProperties = properties .Where(fieldInfo => Attribute.IsDefined(fieldInfo, typeof(ReferenceAttribute))); foreach (var info in referencedProperties) { var referenceName = info.PropertyType.Name; var referenceInstance = FindInstance(referenceName) ?? throw new Exception(); info.SetValue(instance, referenceInstance); } }
private static IEnumerable <IPropertyMapping> GetPropertyMappings(this IReflect type) { var properties = type .GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); return(properties .Where(property => property.GetAttributeValue((NotMappedAttribute key) => key) == null) .Select(property => { var fk = property.GetAttributeValue((ForeignKeyAttribute key) => key); var map = new PropertyMapping { PropertyName = property.Name, ColumnName = property.GetAttributeValue((ColumnAttribute column) => column.Name) ?? property.Name, IsPk = property.GetAttributeValue((KeyAttribute key) => key) != null, IsDbGenerated = property.GetAttributeValue((DatabaseGeneratedAttribute dbGenerated) => dbGenerated.DatabaseGeneratedOption != DatabaseGeneratedOption.None), IsFk = fk != null, RelatedProperty = fk?.Name, IsNavigation = !IsValueProperty(property), PropertyInfo = property }; return map; } )); }
private IEnumerable <Action <IComponentContext, object> > BuildPropertyInjectorCollection(IReflect componentType) { // Look for settable properties of type "ILogger" var properties = componentType .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance) .Select(property => new { PropertyInfo = property, property.PropertyType, IndexParameters = property.GetIndexParameters().ToArray(), Accessors = property.GetAccessors(false) }) .Where(property => property.PropertyType == typeof(ILogger)) // must be a logger .Where(property => property.IndexParameters.Length == 0) // must not be an indexer .Where(property => property.Accessors.Length != 1 || property.Accessors[0].ReturnType == typeof(void)); //must have get/set, or only set // Return an array of actions that resolve a logger and assign the property foreach (var entry in properties) { var property = entry.PropertyInfo; yield return((context, instance) => { var logger = GetCachedLogger(componentType, context); property.SetValue(instance, logger, null); }); } }
private static PropertyInfo FindProperty(IReflect WhereLooking, Type WhatLooking) { try { var propertyInfos = WhereLooking.GetProperties(BindingFlags.Public | BindingFlags.Static) .Where(m => m.PropertyType == WhatLooking).ToArray(); if (propertyInfos.Length > 0) { foreach (var pinfo in propertyInfos) { if (!pinfo.Name.StartsWith("prop_")) { continue; } return(pinfo); } return(propertyInfos.First()); } MelonLogger.Error("[FindInstance] MethodInfo for " + WhatLooking.Name + " is null"); } catch (Exception e) { MelonLogger.Error($"[FindInstance] {e}"); } return(null); }
private static IEnumerable<Action<IComponentContext, object>> BuildLoggerInjectors(IReflect componentType) { // look for settable properties of type "ILogger" var loggerProperties = componentType .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance) .Select(p => new { PropertyInfo = p, p.PropertyType, IndexParameters = p.GetIndexParameters(), Accessors = p.GetAccessors(false) }) // must be a logger .Where(x => x.PropertyType == typeof(ILogger)) // must not be an indexer .Where(x => x.IndexParameters.Count() == 0) // must have get/set, or only set .Where(x => x.Accessors.Length != 1 || x.Accessors[0].ReturnType == typeof(void)); // return an IEnumerable of actions that resolve a logger and assign the property return loggerProperties .Select(entry => entry.PropertyInfo) .Select(propertyInfo => (Action<IComponentContext, object>)((ctx, instance) => { var propertyValue = ctx.Resolve<ILogger>(new TypedParameter(typeof(Type), componentType)); propertyInfo.SetValue(instance, propertyValue, null); })); }
private static IDictionary <string, PropertyMetaData> GetProperties(VisitorState state, IReflect classType, object source) { var className = classType.UnderlyingSystemType.Name; foreach (var property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var value = property.GetValue(source); var key = className + "." + property.Name; if (property.PropertyType.IsPrimtiveType()) { if (state.CanVisit(key)) { state.Placeholders.Add(key, GetPropertyMetaData(property, value)); } } else if (state.CanVisit(value)) { state.Visited.Add(value); GetProperties(state, property.PropertyType, value); } } return(state.Placeholders); }
private static IEnumerable <PropertyInfo> GetILogProperties(IReflect instanceType) { var instanceProperties = instanceType.GetProperties(RelevantProeprties); var writableLogProperties = instanceProperties.Where(IsWritableLogProperty); return(writableLogProperties); }
private static IEnumerable <Action <IComponentContext, object> > BuildPropertiesInjectors(IReflect componentType, IEnumerable <PropertyEntry> properties) { var settableProperties = componentType .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance) .Select(p => new { PropertyInfo = p, IndexParameters = p.GetIndexParameters(), Accessors = p.GetAccessors(false), PropertyEntry = properties.FirstOrDefault(t => t.Name == p.Name) }) .Where(x => x.PropertyEntry != null) .Where(x => !x.IndexParameters.Any()) .Where(x => x.Accessors.Length != 1 || x.Accessors[0].ReturnType == typeof(void)); foreach (var entry in settableProperties) { var propertyInfo = entry.PropertyInfo; var propertyEntry = entry.PropertyEntry; yield return((ctx, instance) => { object value; if (ChangeToCompatibleType(propertyEntry.Value, propertyInfo.PropertyType, out value)) { propertyInfo.SetValue(instance, value, null); } }); } }
/// <summary> /// Get property list of type /// </summary> /// <param name="selfType"></param> /// <param name="ignoreList"></param> /// <returns></returns> public static IEnumerable <string> GetTypeProperties(this IReflect selfType, ICollection <string> ignoreList) { return(selfType.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(pi => !ignoreList.Contains(pi.Name) && pi.GetUnderlyingType().IsSimpleType() && pi.GetIndexParameters().Length == 0) .Select(pi => pi.Name) .ToList()); }
private static IEnumerable <(string, Type)> GetInnerConfigurationProperties(IReflect type) { return(type.GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(property => property.CanRead) .Where(property => property.IsDefined(typeof(ConfigurationAttribute)) || property.PropertyType.IsDefined(typeof(ConfigurationAttribute))) .Select(property => (property.Name, property.PropertyType))); }
public FormatPropertiesResolver(IReflect type, IPropertyFormatInfoProvider formatInfoProvider) { this.formatInfoProvider = formatInfoProvider; PropertiesFormat = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(prop => prop.CanRead) .Select(ConvertToPropertyFormat) .Where(pform => pform != null); }
static List <IMetaDataBinding> ScanForBindings(IReflect messageType) { var bindings = messageType.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(property => property.CanRead && property.CanWrite) .SelectMany(MakeBindings) .ToList(); return(bindings); }
private static PropertyInfo FindUserProperty(IReflect type) { //寻找类型为 "Localizer" 并且具有set方法的属性。 return type .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance) .Where(x => x.PropertyType == typeof(Localizer)) //必须是一个本地化委托 .Where(x => !x.GetIndexParameters().Any()) //没有索引器 .FirstOrDefault(x => x.GetAccessors(false).Length != 1 || x.GetAccessors(false)[0].ReturnType == typeof(void)); //必须具有set方法。 }
private static PropertyInfo FindUserProperty(IReflect type) { //寻找类型为 "Localizer" 并且具有set方法的属性。 return(type .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance) .Where(x => x.PropertyType == typeof(Localizer)) //必须是一个本地化委托 .Where(x => !x.GetIndexParameters().Any()) //没有索引器 .FirstOrDefault(x => x.GetAccessors(false).Length != 1 || x.GetAccessors(false)[0].ReturnType == typeof(void))); //必须具有set方法。 }
private static PropertyInfoForExport[] GetProperetiesForExport(IReflect type, Dictionary <string, ExportInfo> exportInfos) { return(type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .GroupJoin(exportInfos, propertyInfo => propertyInfo.Name, exportInfo => exportInfo.Key, (pi, ei) => new { PropertyInfo = pi, ExportInfo = ei.Select(item => new { item.Value.Order, item.Value.ColumnName }) }) .SelectMany(groupJoinItem => groupJoinItem.ExportInfo.DefaultIfEmpty(), (pi, ei) => new { Order = ei != null ? ei.Order : 0, pi.PropertyInfo, ColumnName = ei != null ? ei.ColumnName : string.Empty }) .OrderBy(item => item.Order) .Select(item => new PropertyInfoForExport(item.PropertyInfo, item.ColumnName)) .ToArray()); }
private static Tuple <PropertyInfo, MethodInfo>[] GetForeignProperties(IReflect type) { return(type.GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(p => p.PropertyType.GetInterface(typeof(IDbAggregate).Name) == null && p.PropertyType.GetInterface(typeof(IEnumerable <IDbAggregate>).Name) == null && p.GetCustomAttributes(typeof(DbForeignAttribute), true).Any()) .Select(p => new Tuple <PropertyInfo, MethodInfo>(p, p.GetGetMethod())) .ToArray()); }
private void WritePropertiesDescription(IReflect type, int propertyLevel) { var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var propertyInfo in properties) { var propertyType = propertyInfo.PropertyType; WriteViewDescriptionInner(propertyType, propertyInfo, propertyLevel + 1); } }
void WriteObject(TextWriter writer, object value, IReflect type) { foreach (var property in type .GetProperties(BindingFlags.Instance | BindingFlags.Public)) { var propertyValue = property.GetValue(value, new object[] { }); WriteTag(writer, propertyValue, property, null); } }
private static IEnumerable <MemberInfo> GetPublicMembers(IReflect type) { var flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; var properties = type.GetProperties(flags); var fields = type.GetFields(flags); var members = new MemberInfo[properties.Length + fields.Length]; properties.CopyTo(members, 0); fields.CopyTo(members, properties.Length); return(members); }
private void GenerateProperties(IReflect type, CodeTypeDeclaration contract) { var properties = type .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => _contractGeneratorOptions.IsExcluded(p) == false); foreach (var property in properties) { contract.Members.Add(_memberGenerator.GeneratePropertyDeclaration(property)); } }
private static string LookupResource(IReflect resourceManagerProvider, string resourceKey) { foreach (var staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)) { if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager)) { var resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null); return(resourceManager.GetString(resourceKey)); } } return(resourceKey); // Fallback with the key name }
private static void UpdateForType <T>(IReflect type, T source, T destination, ICollection <string> keys) where T : class { var myObjectFields = type.GetProperties( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); var pattern = @"<([^>]+)>"; foreach (var fi in myObjectFields.Where(info => !keys.Contains(info.Name))) { fi.SetValue(destination, fi.GetValue(source)); } }
/// <summary> /// Inspect the type and return reflection data /// </summary> /// <param name="t">type to inspect</param> /// <returns>all writable public properties</returns> static ReaderPropertyCollection InspectType(IReflect t) { var props = from p in t.GetProperties(BindingFlags.Public | BindingFlags.Instance) where p.CanWrite select new ReaderProperty { Name = p.Name.ToLower(), Type = p.PropertyType, Setter = p.GetSetMethod() }; return(new ReaderPropertyCollection(props.ToList())); }
private void ProcessProperties(IReflect type, IDictionary <int, MemberMetadata> result) { foreach (var property in type.GetProperties(AVAILABLE_BINDING_FLAGS).Where(new MemberSpecification())) { ValidateSerializableProperty(property); var index = GetMemberOffset(property); Guard.AgainstIsTrue <MetadataBuilderException>(result.ContainsKey(index), string.Format(DUBLICATED_OFFSET_ON_MEMBER_MESSAGE_PATTERN, property.Name)); var memberInfo = (IMemberInfo)Activator.CreateInstance( typeof(DeclarativePropertyInfoMember <,>).MakeGenericType(new[] { this._type, property.PropertyType }), new object[] { property }); result.Add(index, this.CreateMemberMetadata(memberInfo, IsSkipped(property))); } }
private static MethodInfo GetPrimaryGetter(IReflect type) { var getters = type.GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(p => p.GetCustomAttributes(typeof(DbPrimaryAttribute), true).Any()) .Select(p => p.GetGetMethod()) .ToArray(); if (getters.Count() != 1) { throw new InvalidAggregateStructure(); } return(getters.Single()); }
private void injectMembers(IReflect type, object instance) { var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(x => x.CanWrite); foreach (var propertyInfo in properties) { propertyInfo.SetValue(instance, _container.Resolve(propertyInfo.PropertyType), null); } var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (var fieldsInfo in fields) { fieldsInfo.SetValue(instance, _container.Resolve(fieldsInfo.FieldType)); } }
private static IEnumerable <string> GetProperties(IReflect myType, BindingFlags flags) { var properties = myType.GetProperties(flags); foreach (var propertyInfo in properties) { var type = ToPrettyString(propertyInfo.PropertyType); if (!returnTypeDictionary.ContainsKey(type)) { returnTypeDictionary[type] = new List <string>(); } returnTypeDictionary[type].Add(propertyInfo.Name); } return(properties.Select(x => x.Name).Distinct()); }
private static Dictionary <string, PropertyInfo> Build(IReflect type, NamingStrategy namingStrategy = null) { var result = new Dictionary <string, PropertyInfo>(); foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { var jsonExclude = property.GetCustomAttribute <JsonIgnoreAttribute>(); if (jsonExclude != null) { continue; } var jsonPropertyName = GetJsonPropertyName(property, namingStrategy); result.Add(jsonPropertyName, property); } return(result); }
private IEnumerable<Action<IComponentContext, object>> BuildLoggerInjectors(IReflect componentType) { //寻找类型为 "ILogger" 并且具有set方法的属性。 var loggerProperties = componentType .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance) .Select(p => new { PropertyInfo = p, p.PropertyType, IndexParameters = p.GetIndexParameters(), Accessors = p.GetAccessors(false) }) .Where(x => x.PropertyType == typeof(ILogger)) //必须是一个日志记录器 .Where(x => !x.IndexParameters.Any()) //没有索引器 .Where(x => x.Accessors.Length != 1 || x.Accessors[0].ReturnType == typeof(void)); //必须具有set方法。 return loggerProperties.Select(entry => entry.PropertyInfo).Select(propertyInfo => (Action<IComponentContext, object>)((ctx, instance) => { var component = componentType.ToString(); var logger = _loggerCache.GetOrAdd(component, key => ctx.Resolve<ILogger>(new TypedParameter(typeof(Type), componentType))); propertyInfo.SetValue(instance, logger, null); })); }
private static IEnumerable<string> GetProperties(IReflect myType, BindingFlags flags) { var properties = myType.GetProperties(flags); foreach (var propertyInfo in properties) { var type = ToPrettyString(propertyInfo.PropertyType); if (!returnTypeDictionary.ContainsKey(type)) returnTypeDictionary[type] = new List<string>(); returnTypeDictionary[type].Add(propertyInfo.Name); } return properties.Select(x => x.Name).Distinct(); }
private PropertyInfo[] GetIndexablePropertyInfos(IReflect type, bool includeContainedStructureMembers) { return includeContainedStructureMembers ? type.GetProperties(PropertyBindingFlags) : type.GetProperties(PropertyBindingFlags).Where(p => HasIdProperty(p.PropertyType) == false).ToArray(); }
private static List<PropertyInfo> GetTombstonedProperties(IReflect viewModelType) { var propertyInfos = viewModelType.GetProperties(BindingFlags.Instance | BindingFlags.Public); var properties = new List<PropertyInfo>(propertyInfos).Where(x => x.IsDefined(typeof (TombstonedAttribute), true)).ToList(); return properties; }
private static IEnumerable<PropertyInfo> GetProperties(IReflect type) { return type.GetProperties(Flags); }
private static IEnumerable<PropertyInfo> GetTestSourcePropertiesFrom(IReflect type) { return type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(IsTestSource); }
private static IEnumerable<PropertyInfo> GetProxyProperties(IReflect hostType) { return hostType .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty); }
private PropertyInfo[] GetIndexablePropertyInfos(IReflect type) { return type.GetProperties(PropertyBindingFlags); }
private static IEnumerable<KeyValuePair<PropertyInfo, DocumentTypePropertyAttribute>> GetPropertiesWithAttributes(IReflect type) { var privateOrPublicInstanceProperties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var propertiesWithPropertyAttributes = privateOrPublicInstanceProperties.Where(propertyInfo => HasAttribute(propertyInfo, typeof(DocumentTypePropertyAttribute))); var propertyAttributeMapping = new Dictionary<PropertyInfo, DocumentTypePropertyAttribute>(); foreach (var property in propertiesWithPropertyAttributes) { var propertyAttribute = (DocumentTypePropertyAttribute)property.GetCustomAttributes(true).SingleOrDefault(attribute => attribute is DocumentTypePropertyAttribute); if (propertyAttribute != null && !propertyAttributeMapping.ContainsKey(property)) { propertyAttributeMapping.Add(property, propertyAttribute); } } return propertyAttributeMapping; }
private static void WriteToInstance(object instance, IReflect type, XContainer xContainer) { foreach (var pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var propertyType = pi.PropertyType; if (propertyType.IsValueType()) { var child = xContainer.Element(pi.Name); if (child == null) continue; if (pi.GetSetMethod(true) == null) continue; var value = XmlValueConverter.Convert(child.Value, propertyType); pi.SetValue(instance, value, null); continue; } if (propertyType.IsClass()) { var propertyInstance = FormatterServices.GetUninitializedObject(propertyType); pi.SetValue(instance, propertyInstance, null); WriteToInstance(propertyInstance, propertyType, xContainer.Element(pi.Name)); continue; } if (propertyType.IsCollection()) { var current = xContainer.Element(pi.Name); if (current == null) return; var itemType = typeof(object); if (propertyType.IsGenericType) { itemType = propertyType.GetGenericArguments()[0]; } var list = itemType.CreateGenericList(); foreach (var item in current.Elements()) { var itemInstance = FormatterServices.GetUninitializedObject(itemType); WriteToInstance(itemInstance, itemType, item); list.Add(itemInstance); } pi.SetValue(instance, list, null); } } }
private static IEnumerable<Action<IComponentContext, object>> BuildPropertiesInjectors(IReflect componentType, IEnumerable<PropertyEntry> properties) { var settableProperties = componentType .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance) .Select(p => new { PropertyInfo = p, IndexParameters = p.GetIndexParameters(), Accessors = p.GetAccessors(false), PropertyEntry = properties.FirstOrDefault(t => t.Name == p.Name) }) .Where(x => x.PropertyEntry != null) .Where(x => !x.IndexParameters.Any()) .Where(x => x.Accessors.Length != 1 || x.Accessors[0].ReturnType == typeof(void)); foreach (var entry in settableProperties) { var propertyInfo = entry.PropertyInfo; var propertyEntry = entry.PropertyEntry; yield return (ctx, instance) => { object value; if (ChangeToCompatibleType(propertyEntry.Value, propertyInfo.PropertyType, out value)) propertyInfo.SetValue(instance, value, null); }; } }