Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Own configuration section in .net application

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 169
    Comment on it

    We always add a key with a value in our XML configuration and read it at run time but we can extend configuration settings in our XML configuration. To do this, we must create a custom configuration section handler. The handler must be a .NET Framework class that inherits from the  System.Configuration.ConfigurationSection class. The section handler interprets and processes the settings that are defined in XML configuration elements in a specific section of a Web.config file.We can read and write these settings through the handler's properties.
     

    Here is our handler : 

    using System.Configuration;
    
    namespace ConfigurableModule
    {
        public class Configuration : ConfigurationSection  
        {
            public static Configuration GetConfiguration()
            {
                Configuration configuration = 
                    ConfigurationManager
                    .GetSection("myConfigurableModule")
                    as Configuration;
    
                if (configuration != null)
                    return configuration;
    
                return new Configuration();
            }
    
            [ConfigurationProperty("message", IsRequired = false)]
            public string Message
            {
                get
                {
                    return this["message"] as string;
                }
            }
        }
    }

     

    Here is our applications configuration file (app.config/web.config).

    <configuration>
        <configSections>
            <section name="myConfigurableModule" type="ConfigurableModule.Configuration, ConfigurableModule"/>
        </configSections>
        <myConfigurableModule message="Hello world!" />
        <!-- Optionally other configuration -->
    </configuration>


    We can get the Message property from the configuration like this:

    string messageFromConfiguration = ConfigurableModule.Configuration.GetConfiguration().Message ;


    Happy coding :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: