zoukankan      html  css  js  c++  java
  • What we can do with App.config?

    Introduction

    This article explains configuration section handlers defined in the System.Configuration namespace and explains how to create custom section handlers by implementing the interface IConfigurationSectionHandler.

    What we can do with App.config?

    A configuration file can contain information that the application reads at run time. We can use configuration sections to specify this information in configuration files. The .NET Framework provides several predefined configuration sections and developers can also create custom configuration sections.

    Configuration sections have two parts: a configuration section declaration and the configuration settings. We can put configuration section declarations and configuration settings in the machine configuration file or in the application configuration file. At run time, section handlers, which are classes that implement the IConfigurationSectionHandler interface, read settings in the machine configuration file first, followed by the application configuration file. Depending on the section handler, either the settings in the application file override the settings in the machine file or the settings from both files are merged.

    Note: It�s not a good practice to specify application settings in machine.config file.

    There are two types of configuration sections:

    • Predefined configuration section (appSettings).
    • User-Defined configuration section(s).

    Predefined configuration Section (appSettings)

    The .NET Framework provides a predefined configuration section called appSettings. This section is declared in the Machine.config file as follows:

    Collapse Copy Code
    <section name="appSettings" 
        type="System.Configuration.NameValueFileSectionHandler, 
          System, Version=1.0.5000.0, Culture=neutral, 
          PublicKeyToken=b77a5c561934e089"/>

    The sample declaration of the appSettings is:

    Collapse Copy Code
    <appSettings file="appSettings.xml"/>

    Application settings are defined in an external file, which should be in the application bin folder.

    A sample appSettings.xml is:

    Collapse Copy Code
    <?xml version="1.0" encoding="utf-8"?> 
    <appSettings>
        <add key="article" value="Configuration Sections"/>
        <add key="author" value="Palanisamy Veerasingam"/>
    </appSettings>

    or we can keep the appSettings in the App.config file itself:

    Collapse Copy Code
    <appSettings>
        <add key="author" value="Palanisamy Veerasingam"/>
        <add key="article" value="Configuration Sections"/>   
    </appSettings>

    ConfigurationSettings.AppSettings is a special property that provides a shortcut to application settings defined in the <appSettings> section of the configuration file. The following example shows how to retrieve the author name defined in the previous configuration section example:

    Collapse Copy Code
    public string GetAuthor()
    {
        return (ConfigurationSettings.AppSettings["author"]);
    }

    User-Defined configuration sections or Custom configuration sections

    Declaring custom configuration sections

    Collapse Copy Code
    <configSections>
        <section name="sampleSection"
        type="System.Configuration.SingleTagSectionHandler" />
    </configSections>

    The <section> element has two properties:

    • The name attribute, which is the name of the element that contains the information the section handler reads.
    • The type attribute, which is the name of the class that reads the information.

    We can specify the following values to this type attribute:

    • System.Configuration.NameValueSectionHandler � Provides name-value pair configuration information from a configuration section and returns System.Collections.Specialized.NameValueCollection object.
    • System.Configuration.DictionarySectionHandler - Reads key-value pair configuration information for a configuration section and returns System.Collections.Hashtable object.
    • System.Configuration.SingleTagSectionHandler - Reads key-value pair configuration information for a configuration section and returns the System.Collections.Hashtable object.
    • System.Configuration.IgnoreSectionHandler - Provides a section handler definition for configuration sections read and handled by systems other than System.Configuration. To access this section, we have to parse the whole App.config XML file.
    • User defined section handlers, which implement System.Configuration.IConfigurationSectionHandler.

    Also, we can use <sectionGroup> tags for more detailed declaration of our sections as follows:

    Collapse Copy Code
    <sectionGroup name="mainGroup">
    <sectionGroup name="subGroup">
        <section ...
    </sectionGroup>
    </sectionGroup>

    I hope that by looking at the sample, you can understand the difference between these handlers. I not yet faced a situation to use IgnoreSectionHandler; in that case using a different file will be a good practice, I think so.

    Declaring user-defined section handlers

    To declare a user-defined section handler, create a class by implementing the interface System.Configuration.IconfigurationSectionHandler.

    A sample class declaration is:

    Collapse Copy Code
    public class MyConfigHandler:IconfigurationSectionHandler{�}

    There is only one method defined in the interface IconfigurationSectionHandler with the following signature:

    Collapse Copy Code
    object Create (object parent, object configContext, XmlNode section)
    • parent - The configuration settings in a corresponding parent configuration section.
    • configContext - An HttpConfigurationContext when Create is called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference.
    • section - The XmlNode that contains the configuration information from the configuration file. Provides direct access to the XML contents of the configuration section.
    • Return value - A configuration object.

    Sample SectionHandler class definition follows:

    Collapse Copy Code
    public class MyConfigHandler:IConfigurationSectionHandler
    {
        public MyConfigHandler(){}
    
        public object Create(object parent, 
               object configContext, System.Xml.XmlNode section)
        {
            CCompanyAddr objCompany=new CCompanyAddr();
            objCompany.CompanyName = section.SelectSingleNode("companyName").InnerText;
            objCompany.DoorNo = section.SelectSingleNode("doorNo").InnerText;
            objCompany.Street = section.SelectSingleNode("street").InnerText;
            objCompany.City = section.SelectSingleNode("city").InnerText;
            objCompany.PostalCode = 
              Convert.ToInt64(section.SelectSingleNode("postalCode").InnerText);
            objCompany.Country = section.SelectSingleNode("country").InnerText;
            return objCompany;
        }
    }

    CCompanyAddr is another class defined with the above used properties with corresponding private members.

    I have declared a section in the App.config file as follows:

    Collapse Copy Code
    <configSections>
        ...
        <sectionGroup name="companyInfo">
        <section name="companyAddress" 
                type="ConfigSections.MyConfigHandler,ConfigSections"/>
        </sectionGroup>
    
    </configSections>

    ConfigSections is the name of the namespace.

    Then the section is declared in App.config file as follows:

    Collapse Copy Code
    <companyInfo> 
        <companyAddress> 
    <companyName>Axxonet Solutions India Pvt Ltd</companyName>
    <doorNo>1301</doorNo>
    <street>13th Cross, Indira Nagar, 2nd Stage</street>
    <city>Bangalore</city>
    <postalCode>560038</postalCode>
    <country>India</country>
        </companyAddress>
    </companyInfo>

    To read companyAddress settings from App.config, we have to use the ConfigurationSettings.GetConfig as follows:

    Collapse Copy Code
    CCompanyAddr obj = 
      (CCompanyAddr)ConfigurationSettings.GetConfig("companyInfo/companyAddress");
    • ConfigurationSettings.GetConfig - Returns configuration settings for a user-defined configuration section.

    Conclusion

    I have written a very simple application to understand these section handlers, so I haven�t commented my code. Feel free to reply.

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here

    About the Author

    Palanisamy Veerasingam


    Member

    Occupation: Architect
    Location: India India
    http://www.codeproject.com/KB/aspnet/ConfigSections.aspx
  • 相关阅读:
    IDEA导入项目后,导入artifacts 方法 以及 Spring的配置文件找不到的解决方法
    Tomcat8中如何内存溢出,如何增大内存?
    SpringSecurity-权限关联与控制
    学习黑马教学视频SSM整合中Security遇到的问题org.springframework.security.access.AccessDeniedException: Access is denied
    SSM项目中,关于Test类中不能使用Autowired注入bean的问题
    spring mvc绑定参数之 类型转换 有三种方式:
    maven缺失ojdbc6解决方案 :Missing artifact com.oracle:ojdbc6:jar:11.2.0.1.0问题解决 ojdbc包pom.xml出错
    学习SpringMVC 文件上传 遇到的问题,403:returned a response status of 403 Forbidden ,409文件夹未找到
    【转】Linux环境搭建FTP服务器与Python实现FTP客户端的交互介绍
    Protocol buffers--python 实践 简介以及安装与使用
  • 原文地址:https://www.cnblogs.com/no7dw/p/1530469.html
Copyright © 2011-2022 走看看