internal static void ValidateElement(ConfigurationElement elem, ConfigurationValidatorBase propValidator, bool recursive) {
// Validate a config element with the per-type validator when a per-property ( propValidator ) is not supplied
// or with the per-prop validator when the element ( elem ) is a child property of another configuration element
ConfigurationValidatorBase validator = propValidator;
if ((validator == null) && // Not a property - use the per-type validator
(elem.ElementProperty != null)) {
validator = elem.ElementProperty.Validator;
// Since ElementProperty can be overriden by derived classes we need to make sure that
// the validator supports the type of elem every time
if ((validator != null) && !validator.CanValidate(elem.GetType())) {
throw new ConfigurationErrorsException(SR.GetString(SR.Validator_does_not_support_elem_type, elem.GetType().Name));
}
}
try {
if (validator != null) {
validator.Validate(elem);
}
}
catch (ConfigurationException) {
// ConfigurationElement validators are allowed to throw ConfigurationErrorsException.
throw;
}
catch (Exception ex) {
throw new ConfigurationErrorsException(SR.GetString(SR.Validator_element_not_valid, elem._elementTagName, ex.Message));
}
catch {
throw new ConfigurationErrorsException(SR.GetString(SR.Validator_element_not_valid, elem._elementTagName, ExceptionUtil.NoExceptionInformation));
}
if (recursive == true) {
if (elem is ConfigurationElementCollection) {
if (elem is ConfigurationElementCollection) {
IEnumerator it = ((ConfigurationElementCollection)elem).GetElementsEnumerator();
while( it.MoveNext() ) {
ValidateElement((ConfigurationElement)it.Current, null, true);
}
}
}
// Validate all child elements recursively
for (int index = 0; index < elem.Values.Count; index++) {
ConfigurationElement value = elem.Values[index] as ConfigurationElement;
if (value != null) {
// Run the per-type validator on the child element and proceed with validation in subelements
// Note we dont run the per-property validator here since we run those when the property value is set
ValidateElement(value, null, true); // per-type
}
}
}
}