Własna sekcja konfiguracyjna w web.config

by Piotrosz 6. March 2010
Przykład własnej sekcji konfiguracyjnej w pliku Web.Config. Najpierw napiszę, co chcę zrobić: chciałbym dopisać sobie do Web.Config taką własną sekcję:
  <MyConfSection1 setting1="Hałabała">
    <languages>
      <add name="Russian" fluency="3"/>
      <add name="Spanish" fluency="2"/>
      <add name="CSharp" fluency="2"/>
    </languages>
  </MyConfSection1>
A potem w odczytać ją sobie w kodzie:
string Ustawienie1 = CustomConfigSection.Config.Setting1;
Debug.WriteLine(Ustawienie1);

foreach (LanguageConfigurationElement elem in CustomConfigSection.Config.Languages)
{
    Debug.WriteLine(elem.Name);
    Debug.WriteLine(elem.Fluency);
}
Oto klasa, która to umożliwi:
using System;
using System.Configuration;

namespace ConfigSectionsTest
{
    public class CustomConfigSection : ConfigurationSection
    {
        private CustomConfigSection() { }

        private static CustomConfigSection _Config = ConfigurationManager.GetSection("MyConfSection1") as CustomConfigSection;
        public static CustomConfigSection Config
        {
            get { return _Config; }
        }

        // Ustawienie pojedyncze
        // <MyConfSection1 Setting1="costam"></MyConfSection1>
        [ConfigurationProperty("setting1", DefaultValue = "Domyślna wartość", IsRequired = true)]
        public string Setting1
        {
            get { return this["setting1"] as string; }
        }

        // Ustawienie - kolekcja
        // <MojaSekcja1 ...>
        // <Languages>
        // <add Name="Russian" Fluency="3"/>
        // <add Name="Spanish" Fluency="2"/>
        // </Languages>
        // </MojaSekcja1>
        [ConfigurationProperty("languages")]
        public LanguagesConfigurationCollection Languages
        {
            get { return this["languages"] as LanguagesConfigurationCollection; }
        }
    }

    // Pojedynczy element kolekcji
    public class LanguageConfigurationElement : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true, DefaultValue="")]
        [StringValidator(InvalidCharacters=";:><?*&%^$#@!")]
        public string Name
        {
            get { return this["name"] as string; }
        }

        [ConfigurationProperty("fluency", IsRequired = true, DefaultValue=1)]
        [IntegerValidator(MinValue=1, MaxValue=5, ExcludeRange=false)]
        public int Fluency
        {
            get { return Convert.ToInt32(this["fluency"]); }
        }
    }

    // Zdefiniowanie kolekcji
    public class LanguagesConfigurationCollection : ConfigurationElementCollection
    {
        public LanguageConfigurationElement this[int index]
        {
            get { return base.BaseGet(index) as LanguageConfigurationElement; }
            set 
            {
                if (base.BaseGet(index) != null)
                    base.BaseRemoveAt(index);
                this.BaseAdd(index, value);
            }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new LanguageConfigurationElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((LanguageConfigurationElement)element).Name;
        }
    } 
}
Tutaj następuje jedna ciekawostka. Jeśli w tym fragmencie kodu:
[ConfigurationProperty("fluency", IsRequired = true, DefaultValue=1)]
[IntegerValidator(MinValue=1, MaxValue=5, ExcludeRange=false)]
Nie będzie ustawiona DefaultValue=1, to będzie zawsze rzucany wyjątek, mimo iż w Web.Config odpowiednia wartość "fluency" będzie z poprawnego zakresu!

Wynik w oknie Output po odpaleniu tego przykładu:
Hałabała
Russian
3
Spanish
2
CSharp
2

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen