Tuesday, November 25, 2014

Find Custom Config Section in web.config by Type instead of by String

Instead of calling Configuration ConfigurationManager.GetSection("name of section"), call the following:

CustomSection section = GetConfigSection(typeof(CustomSection)) as CustomSection;

This way, you don't have to hard code the name of the section into your code and it allows who ever is consuming your code to change section names and group them as they see fit.

You'll need to add the following code for the above function. You could add it to your config class and add strong typing or you could add it to a utility class.



/// <summary>
/// Instead of getting the config section by name, use this to get the config section by type. It will return the first section with a matching type. 
/// Thus if there are multiple sections with the same type, it will only return the first one.
/// Call like CustomMailWebEventProviderSection section = GetConfigSection(typeof(CustomMailWebEventProviderSection)) as CustomMailWebEventProviderSection;
/// </summary>
/// <param name="configSectiontype">Type of config section you're looking for</param>
/// <returns>Config section of the specified type or null if no section of that type is found</returns>
public ConfigurationSection GetConfigSection( Type configSectiontype )
{
    // Set it up and call recursive function
    Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
 
    return GetConfigSection(configSectiontype, config.Sections, config.SectionGroups);
}
        
// returns first config section that matchs the type we're looking for
public ConfigurationSection GetConfigSection(Type configSectiontype, ConfigurationSectionCollection sections, ConfigurationSectionGroupCollection groups)
{
    if (sections != null)
    {
        foreach (ConfigurationSection section in sections)
        {
            if (section.GetType() == configSectiontype)
            {
                return section;
            }
        }
    }
    if (groups != null)
    {
        foreach (ConfigurationSectionGroup group in groups)
        {
            ConfigurationSection section = GetConfigSection(configSectiontype, group.Sections, group.SectionGroups);
            if (section != null)
            {
                return section;
            }
        }
    }
 
    //section not found
    return null;
}

No comments:

Post a Comment