Как программно добавить секцию Group в web.config - PullRequest
2 голосов
/ 06 января 2011

Фон

Я хочу вставить следующее в мой web.config

  <sectionGroup name="elmah">
    <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah"/>
    <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
    <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/>
  </sectionGroup>

(нет призов за то, что я угадал, чего я пытаюсь достичь!), Но я запутался. Документы на MSDN предполагают, что мне нужно создать подкласс ConfurationSection, если я хочу добавить его в группу. Я написал себе небольшое приложение для Windows, чтобы помочь мне понять это, но я не очень далеко! Вот соответствующий код, который пытается добавить только раздел «Безопасность».

private void AddElmahSectionGroup()
{
    string exePath = Path.Combine(Environment.CurrentDirectory, "NameOfExe.exe");
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(exePath);

    ConfigurationSectionGroup elmahGroup = configuration.GetSectionGroup(elmahSectionGroupName);
    if (elmahGroup != null)
    {
        Console.WriteLine("sectionGroup with name {0} already in web.config", elmahSectionGroupName);
        return;
    }
    elmahGroup = new ConfigurationSectionGroup();
    configuration.SectionGroups.Add(elmahSectionGroupName, elmahGroup);

    var securitySection = new Section { Name = "security", RequirePermission = false, Type = "Elmah.SecuritySectionHandler, Elmah" };
    elmahGroup.Sections.Add("security", securitySection);

    configuration.Save();
}

public class Section : ConfigurationSection
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name { get { return (String)this["name"]; } set { this["name"] = value; } }

    [ConfigurationProperty("requirePermission", IsRequired = true)]
    public bool RequirePermission { get { return (bool)this["requirePermission"]; } set { this["requirePermission"] = value; } }

    [ConfigurationProperty("type", IsRequired = true)]
    public string Type { get { return (string)this["type"]; } set { this["type"] = value; } }
}

И вот результирующий файл конфигурации

    <?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <sectionGroup name="elmah" type="System.Configuration.ConfigurationSectionGroup, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" >
            <section name="security" type="ConfigEditing.Form1+ElmahLogic+Section, ConfigEditing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
        </sectionGroup>
    </configSections>
    <elmah>
        <security name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
    </elmah>
</configuration>

Который полностью вывернул мою дыню: -

  • Прежде всего type элемента section - это тип моего класса (производный от ConfigurationSection)
  • секунду, добавив определение sectionGroup в группу, я (одновременно) добавив группу в конфигурацию.

Я не очень удивлен этими результатами, потому что я действительно не понимаю API, но я просто не нашел приличных документов о том, что я хочу сделать. Может ли кто-нибудь здесь помочь - даже если он просто указывает мне на пример MSDN, который является действительно полным рабочим примером.

1 Ответ

2 голосов
/ 07 января 2011

Простой пример, который добавляет в app.config раздел, подобный следующему:

//<configSections>
//  <sectionGroup name="elmah" type="Overflow.CustomConfigurationSectionGroup, Overflow, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" >
//  </sectionGroup>
//</configSections>

namespace Overflow
{
    public class CustomSecuritySection : ConfigurationSection
    {
    }

    public class CustomConfigurationSectionGroup : ConfigurationSectionGroup
    {
        public CustomConfigurationSectionGroup()
        {
            Security = new CustomSecuritySection();
        }

        [ConfigurationProperty("security")] 
        public CustomSecuritySection Security { get; private set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var config = ConfigurationManager.OpenExeConfiguration(Path.Combine(Application.StartupPath, Application.ProductName + ".exe"));

            config.SectionGroups.Add("elmah", new CustomConfigurationSectionGroup());

            config.Save(ConfigurationSaveMode.Modified);

        }
    }
}
...