Вложенные пользовательские элементы в app.config (C #) - PullRequest
5 голосов
/ 07 апреля 2011

Да всем,

В течение нескольких часов я пытался понять, как читать настройки из app.config file:

<?xml version="1.0"?>
<configuration>

  <configSections>
    <section name="Databases" type="McFix.DatabaseSection, McFix"/>
  </configSections>

  <Databases>
    <Database name="database">
      <Tables>
        <Table name="be_sessions">
          <Columns>
            <Column name="sess_id">
            </Column>
          </Columns>
        </Table>
      </Tables>
    </Database>
  </Databases>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

Код для пользовательских классов обработчиков: здесь , также скопирован ниже:

public class DatabaseSection : ConfigurationSection
{
    [ConfigurationProperty("Databases", IsDefaultCollection = false)]
    public DatabaseInstanceCollection Databases
    {
        get { return (DatabaseInstanceCollection)this["Databases"]; }
        set { this[""] = value; }
    }
}
[ConfigurationCollection(typeof(DatabaseElement), AddItemName = "add", CollectionType = ConfigurationElementCollectionType.BasicMap )]
public class DatabaseInstanceCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new DatabaseElement();
    }
    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((DatabaseElement)element).Name;
    }
}
public class DatabaseElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
    public string Name
    {
        get { return (string)base["name"]; }
        set { base["name"] = value; }
    }
}

public class TableSection : ConfigurationSection
{
    [ConfigurationProperty("Tables", IsDefaultCollection = true)]
    public TableInstanceCollection Tables
    {
        get { return (TableInstanceCollection)this["Tables"]; }
        set { this[""] = value; }
    }
}

[ConfigurationCollection(typeof(TableElement), AddItemName = "Table", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class TableInstanceCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new TableElement();
    }
    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((TableElement)element).Name;
    }
}

public class TableElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
    public string Name
    {
        get { return (string)base["name"]; }
        set { base["name"] = value; }
    }
}

public class ColumnSection : ConfigurationSection
{
    [ConfigurationProperty("Columns", IsDefaultCollection = true)]
    public ColumnInstanceCollection Columns
    {
        get { return (ColumnInstanceCollection)this["Columns"]; }
        set { this[""] = value; }
    }
}

[ConfigurationCollection(typeof(ColumnElement), AddItemName = "Column", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class ColumnInstanceCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new ColumnElement();
    }
    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((ColumnElement)element).Name;
    }
}

public class ColumnElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
    public string Name
    {
        get { return (string)base["name"]; }
        set { base["name"] = value; }
    }
}

Проблема в том, что я пытаюсь получить раздел «Базы данных» с помощью метода GetSection:

Configuration Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
DatabaseSection DbConfig = Config.GetSection("Databases") as DatabaseSection;

Программа генерирует исключение ConfigurationErrorsException, сообщая «Нераспознанный элемент« База данных »», хотя это происходит после прохождения метода get DatabaseSection, хотя я определяю AddItemName для DatabaseInstanceCollection как «База данных». Я что-то упустил, атрибут, который позволит базовому коду правильно читать app.config?

Ответы [ 2 ]

7 голосов
/ 08 апреля 2011

Обязательные ссылки:

После беглого взгляда кажется, что ваша проблема в этой строке:

[ConfigurationCollection(typeof(DatabaseElement), AddItemName = "add", CollectionType = ConfigurationElementCollectionType.BasicMap )]

Это означает, что файл .config должен выглядеть следующим образом:

<Databases>
    <add><!-- Database goes here --></add>
</Databases>

Т.е. ваш элемент Databases ожидает дочернего элемента "add", что указывает на то, что элемент должен быть добавлен в коллекцию.

Вы должны попробовать изменить свойство AddItemName с «add» на «Database»:

[ConfigurationCollection(typeof(DatabaseElement), AddItemName = "Database", CollectionType = ConfigurationElementCollectionType.BasicMap )]

(у меня не было возможности проверить это, могут быть другие проблемы)

1 голос
/ 08 апреля 2011

Вы правы, Краген, мне пришлось удалить Table / ColumnSection и добавить Table / ColumnInstanceCollection в Database / TableElement.Свойство DatabaseSection 'Базы данных должно быть таким:

[ConfigurationProperty("", IsDefaultCollection = true)]
        public DatabaseInstanceCollection Databases
        {
            get { return (DatabaseInstanceCollection)this[""]; }
        }
...