How to create nested custom configuration section in c#?
Asked Answered
J

1

6

I need custom configuration in following way

<root>
<group>
 <groupitem> 
    <property1/>
    <property2/>
    <property3/>
    <property4/>   
 </groupitem>
<group>
</root>

I am not finding any example of how to do that.

Following comes very close,

Nested Configuration Section app.config

but still I am stuck on defining class corresponding to groupitem. If I change property1, property2 from element to attribute, that is easy to define.

But that will create problem if these properties have nested properties.

Question is, How to define the nested hierarchy in the way defined above?

Jurisconsult answered 15/1, 2013 at 8:45 Comment(0)
P
6

The configuration section is the top-level element of some configuration model. For example, your product name would be the configuration section.

Any other nested element is a ConfigurationElement or ConfigurationElementCollection.

Actually you can also create custom section groups deriving ConfigurationSectionGroup.

Taking your configuration:

<root> <!-- This is a ConfigurationSection -->
<group><!-- This is a ConfigurationElement -->
 <groupitem> <-- This could be a ConfigurationElement having child items of type ConfigurationElement or a ConfigurationElementCollection -->
    <property1/> <!-- This is a ConfigurationElement -->
    <property2/> <!-- This is a ConfigurationElement -->
    <property3/> <!-- This is a ConfigurationElement -->
    <property4/> <!-- This is a ConfigurationElement -->   
 </groupitem>
<group>

If you really want to know how to work with .NET configuration model, take a look at these articles:

Planoconvex answered 15/1, 2013 at 9:40 Comment(7)
root could be a ConfigurationSectionGroup and group a ConfigurationSectionTraveler
@Traveler Yeah, who knows... It could be, or not... I'm just trying to illustrate OP with a sample.Tracheo
@MatíasFidemraizer, Your comments are better. The link you have shared have all created rather simple custom configuration section (and not the complex one). I have done with your comments, now evaluating another approachJurisconsult
@Jurisconsult I'd suggest you to go with the standard approach.Tracheo
For anyone else coming across this Stackoverflow post I've read the two articles linked to by Matias. The Writing a Complex Custom Configuration Section article is particularly useful if you want to create a container element containing a collection one or more child elements of the same type. Think something like a custom AppSettings section, which can have multiple settings with within it.Haviland
The 2 links may be helpful and possibly even recommended, but they do not contain information regarding the "nested" hierarchy requested.Lulululuabourg
this link illustrates the code needed. Unfortunately it is incomplete: hoanghaivm.wordpress.com/net/custom-configuration-for-net-20Lulululuabourg

© 2022 - 2024 — McMap. All rights reserved.