Create a Custom Configuration Sections in configs

Hi everyone!
Today I want to talk you about Custom Configuration Section in app.configs or web.configs.

Our business situation:
We want to create a custom section about countries and continents. We have the following information:

CountryContinent
ArgentinaAmerica
New ZealandOceania
SpainEurope
ChinaAsia
South Africa Africa

FIRST APPROACH

Use a list of key value pairs in the appSettings section, like this:

Then If I want to access to Argentina value, we’d only need to use the following code:

If we want to get all countries, we”ll have to code something like this:

This approach isn’t good in our situation because we have a hardcoding list. If tomorrow day we’d insert a new country in the app.config we must modify this method and add the new country in that.
Conclusion: this approach doesn’t work with a dynamic list of countries.

SECOND APPROACH

In this approach, we’ll use a custom configuration section but we’re keeping the key-value pair idea. For that we’ll use the built-in type NameValueSectionHandler

Steps:
1) Set the custom section: AppCountries un the ConfigSection

2)Create section AppCountries and specify the key-value pairs.

3) Access to data!

With this approach we can separate our keys in a specific section, that is good! In addition, we can list all values inside the section. In other words, this section contains specific values about the countries&continents.
This approach isn’t bad! But there isn’t sematic power. With that we can only specify key and value, but if we want to specify more values ? or if we want to add more keys with others names for example: conuntryName, continent, CountryId instead of only “key ” and “value”? Let’s continue!

THIRD APPROACH

The before aptions are functional and worked but, Would you rather see something more like this ?

This approach is more complex but more semantic-rich.
We have to build our own types. Let’s begin

1) Set a new section in the ConfigSection (AppCountriesSection). We have to specify our own type (fully path to our new configuration class) & the assembly name where our new class is in.

2) Generate de section and specify de values!

3) Create our custom configuration classes –> These classes teach to the framework how to read our custom configuration section

4) Finally we’ll read the values from the section

This approach is great! It’s a bit complex but we win clarity and legibility. We don’t mix a specify section with app.settings keys.

ALL APP.CONFIG:

Completed example:
https://github.com/morales-franco/JungleApp [Custom Sections in App.Settings (Batch project))]

See you later!
F.M