How to register a new Section Definition using Microsoft.Web.Administration

Today I was asked how can someone would be able to add a new section definition using Microsoft.Web.Administration, so I thought I would post something quickly here just to show how this could be achieved.

using System;
using Microsoft.Web.Administration;

class Program {
    static void Main(string[] args) {
        using (ServerManager m = new ServerManager()) {
            Configuration config = m.GetApplicationHostConfiguration();

            SectionDefinition definition =
                RegisterSectionDefinition(config, "system.webServer/mySubgroup/mySection");
            definition.OverrideModeDefault = "Allow";

            m.CommitChanges();
        }
    }

    public static SectionDefinition RegisterSectionDefinition(Configuration config, string sectionPath) {
        string[] paths = sectionPath.Split('/');

        SectionGroup group = config.RootSectionGroup;
        for (int i = 0; i < paths.Length - 1; i++) {
            SectionGroup newGroup = group.SectionGroups[paths[i]];
            if (newGroup == null) {
                newGroup = group.SectionGroups.Add(paths[i]);
            }
            group = newGroup;
        }

        SectionDefinition section = group.Sections[paths[paths.Length - 1]];
        if (section == null) {
            section = group.Sections.Add(paths[paths.Length - 1]);
        }

        return section;
    }
}

The idea is that you can grab a Configuration object they usual way, it could be ApplicationHost.config or any web.config, and then you call the method RegisterSectionDefinition which will ensure the whole hierarchy is added (in the case of multiple nested Section Groups) and then it will return the newly added Section Definition that you can then use to change any of their properties.

A very similar functionality is exposed for scripts and native code in the AHADMIN COM library exposing the RootSectionGroup as well from any IAppHostConfigFile that you can manipulate in the same way.

Hope this helps,