private static void ApplyInstanceAttributes(object instance) {
Debug.Assert(instance is ConfigurationElement, "instance is ConfigurationElement");
Type type = instance.GetType();
foreach (PropertyInfo propertyInformation in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
ConfigurationPropertyAttribute attribProperty =
Attribute.GetCustomAttribute(propertyInformation,
typeof(ConfigurationPropertyAttribute)) as ConfigurationPropertyAttribute;
if (attribProperty != null)
{
Type propertyType = propertyInformation.PropertyType;
// Collections need some customization when the collection attribute is present
if (typeof(ConfigurationElementCollection).IsAssignableFrom(propertyType)) {
ConfigurationCollectionAttribute attribCollection =
Attribute.GetCustomAttribute(propertyInformation,
typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
// If none on the property - see if there is an attribute on the collection type itself
if (attribCollection == null) {
attribCollection =
Attribute.GetCustomAttribute(propertyType,
typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
}
ConfigurationElementCollection coll = propertyInformation.GetValue(instance, null) as ConfigurationElementCollection;
if (coll == null) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_element_null_instance,
propertyInformation.Name, attribProperty.Name));
}
// If the attribute is found - get the collection instance and set the data from the attribute
if (attribCollection != null) {
if (attribCollection.AddItemName.IndexOf(',') == -1) {
coll.AddElementName = attribCollection.AddItemName;
}
coll.RemoveElementName = attribCollection.RemoveItemName;
coll.ClearElementName = attribCollection.ClearItemsName;
}
}
else if (typeof(ConfigurationElement).IsAssignableFrom(propertyType)) {
// Nested configuration element - handle recursively
object element = propertyInformation.GetValue(instance, null);
if (element == null) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_element_null_instance,
propertyInformation.Name,attribProperty.Name));
}
ApplyInstanceAttributes(element);
}
}
}
}