Rozdelenie app.config do suborov podla sekcii

Aj o trochu vacsia aplikacia v .NET si vyzaduje aspon niekolko nastaveni, ktore by sme radi zmenili uz v skompilovanom kode. Existuje niekolko moznosti, ako tieto nastavenia ulozit v konfiguracnych suboroch alebo inom mieste. Asi najstarsi a mozno najjednoduchsi je pouzit subor app.config (web.config). Problem pouzivania tychto suborov je, ze pri vacsej aplikacii sa subor nafukne do neprehladnych rozmerov. Skusme ho teda rozdelit do viacerych suborov podla Section ku ktorej patria.

V app.config pridame do configuration nody:

<configSections>
 <sectionGroup name="customSettings">
 <section name="gameParts" type="MyClasses.GamePartsSection, MyAssemblyName"/>
 </sectionGroup>
</configSections>

Dalej samotne nastavenie (tiez v app.config)

<customSettings>
 <gameParts configSource="GameParts.config" />
</customSettings>

V subore GameParts.config bude povodny obsah gameParts nody.

<?xml version="1.0" encoding="utf-8" ?>
<gameParts periodName="Tretina">
  <times>
    <add name="Play" value="-0:20:00"/>
    <add name="Intermission" value="0:18:00"/>
    <add name="Overtime" value="0:5:00"/>
  </times>
</gameParts>

Pre to, aby nam tato sekcia vobec fungovala potrebujeme este vyrobit triedu

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
 
namespace MyClasses
{
  public class GamePartsSection : ConfigurationSection
  {
    [ConfigurationProperty("times", IsDefaultCollection = true)]
    public NameValueConfigurationCollection GamePartsTimes
    {
      get
      {
        return (NameValueConfigurationCollection)base["times"];
      }
    }
 
    [ConfigurationProperty("periodName")]
    public string GamePartName
    {
      get
      {
        return (string)base["periodName"];
      }
    }
  }
}

Cele to vytiahneme takymto kodom.

GamePartsSection section = ConfigurationManager.GetSection("customSettings/gameParts") as GamePartsSection;
      if (section != null)
      {
        var gamePartsTimes = section.GamePartsTimes;
        var gamePartName = section.GamePartName;
        //... a ulozime si to napr. do statickych premennych
      }

Vyhoda pouzivania vlastnych Section oproti systemovej sekcii appSettings je v oddeleni semantickych celkov, moznosti pouzivania inych typov ako len string a vyssej modularite. Mnozstvo kodu na to potrebne je tiez minimalne. Ked si pridame moznost vynat si celu sekciu do ineho suboru, dostaneme vcelku pouzitelny system.

This entry was posted in Nezaradené, Programovanie and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">