65.9K
CodeProject 正在变化。 阅读更多。
Home

智能设备应用程序的配置管理

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.42/5 (20投票s)

2004年4月5日

CPOL

5分钟阅读

viewsIcon

79174

downloadIcon

789

该实用程序可帮助您配置 .NET Compact Framework 应用程序。

引言

.NET Framework 为开发人员和管理员提供了对应用程序运行方式的控制和灵活性。管理员可以控制应用程序可以访问的受保护资源、应用程序将使用的程序集版本以及远程应用程序和对象的位置。开发人员可以将设置放入配置文件中,从而无需在每次更改设置时重新编译应用程序。

但出于未知原因,.NET Compact Framework 开发人员无法使用此功能。本实用程序旨在实现 .NET Compact Framework 应用程序配置的类似灵活性,开发人员可以将设置放入名为 SmartConfig.xml 的 XML 配置文件中,从而无需在每次更改设置时重新编译应用程序。

此实用程序模仿 .NET Framework 的配置管理方式(定义和使用方式),在运行时获取信息,但它在处理开发人员定义的自定义 configSections 方面非常精确。它没有任何预定义的配置节,例如 <system.diagnostics>

SmartDeviceUtilities.ConfigurationManagement 程序集包含各种类定义和接口,可用于在以 .NET Compact Framework 为目标的应用中实现配置管理任务。

关于 SmartDeviceUtilities.ConfigurationManagement 程序集

  • ConfigurationSettings 类 - 提供对指定配置节中配置设置的访问。此类公开了一个公共静态方法 GetConfig(),该方法以字符串类型作为参数接受配置节节点的名称,并返回声明为 SmartConfig.xml 中该节节点处理程序的类型名称的实例。
    此类还公开了一个公共静态属性 AppSettings,它返回一个 NameValueCollection,其中填充了 SmartConfig.xml 文件中 appSettings 节定义的键值对。
  • ConfigurationSectionHandlerActivator 类:此类定义了一个名为 ReadConfigurationSettings() 的内部静态方法,该方法负责激活各种配置节节点中定义的节处理程序。
  • IConfigSectionHandler 接口:定义了所有智能设备配置节处理程序必须实现才能参与配置设置解析的契约。
  • ReadOnlyNameValueCollection 类 - 派生自 NameValueCollection。此类公开了一个公共方法 SetReadOnly(),调用后会将集合标记为“只读”。

背景

配置文件可以包含应用程序在运行时读取的信息。开发人员使用配置节在配置文件中指定此信息。配置节包含两个部分:配置节声明和配置设置。您可以将配置节声明和配置设置放入 SmartConfig.xml 文件中。

运行时,实现 IConfigSectionHandler 接口的类(节处理程序)会读取 SmartConfig.xml 中的设置。

除了支持自定义配置节外,SmartConfig.xml 还定义了一个名为 appSettings 的默认节,它是一个由 keyvalue 属性定义的节点集合。无需为 appSettings 配置节编写单独的处理程序,因为此节将被内部处理,并且可以通过 ConfigurationSettings 类的公共静态 AppSettings 属性进行访问。

SmartConfig.xml - 配置节的架构

<configuration>
   <appSettings>
   <configSections>
      <section>
   <Custom element for configuration section>
   <Custom element for configuration section>

它是如何工作的?

定义为配置节处理程序的类应实现 IConfigSectionHandler 接口。通过定义 IConfigSectionHandler.Create 方法,该类被指定为有效的配置节处理程序。当客户端代码调用静态 ConfigurationSettings.GetConfig(sectionName) 方法以获取特定配置节的配置设置时,该方法会读取静态 ConfigurationSectionHandlerActivator.IsActivated 属性,如果配置节处理程序已激活,则返回 true。如果属性返回 false,则会调用静态 ConfigurationSectionHandlerActivator.ReadConfigurationSettings() 方法,该方法会读取 SmartConfig.xml 并将配置节处理程序对象存储在一个同步版本的 Hashtable 中,以节名称作为键,并将 ConfigurationSectionHandlerActivator.IsActivated 设置为 true,以便后续对 GetConfig 方法的调用直接从 Hashtable 返回值。

ConfigurationSettings.GetConfig(sectionName) 方法定义

    #region GetConfig
    
    /// <summary>
    /// Returns configuration settings for a user-defined configuration 
    /// section.
    /// </summary>
    /// 
    /// <param name="sectionName">The configuration section to read.</param>
    /// 
    /// <returns>The configuration settings for sectionName.</returns>
    public static object GetConfig(String sectionName)
    {
        if (!ConfigurationSectionHandlerActivator.IsActivated)
            ConfigurationSectionHandlerActivator.ReadConfigurationSettings();

        if (configSectionsStore.ContainsKey(sectionName))
            return configSectionsStore[sectionName];
        else
            return null;
     }

     #endregion

ConfigurationSectionHandlerActivator.ReadConfigurationSettings() 方法还会读取 SmartConfig.xml 文件中的 appSettings 节,并将键值对存储在 ReadOnlyNameValueCollection 对象中。
可以通过公共索引器或 Get(key) 方法访问此键值对,该方法属于由 ConfigurationSettings 类的静态 AppSettings 属性返回的只读 NameValueCollection 对象。

使用代码

本节介绍如何在代码中使用 SmartDeviceUtilities.ConfigurationManagement 程序集。

步骤 1:下载与本文一起发布的源代码文件。

步骤 2:在您的项目中添加对 SmartDeviceUtilities.ConfigurationManagement 的项目或程序集引用。

步骤 3:在项目文件夹中创建一个名为 SmartConfig.xml 的新 XML 文件。

步骤 4:声明配置节并访问配置设置。配置节信息可以分为两个主要部分:配置节声明区域和配置节设置区域。将配置节声明放入 <configSections> 元素中。通过在 <configSections> 元素内的 <section> 元素中声明来创建新配置节。<section> 元素有两个属性:name 属性,这是包含节处理程序读取信息的元素的名称;type 属性,它有两个部分:读取信息的类的名称和包含该类型的程序集,它们之间用“,”(逗号)分隔。配置设置的语法取决于与配置节关联的节处理程序。SmartConfig.xml 还支持一个名为 <appSettings> 的默认配置节,它是一个由 keyvalue 属性定义的节点集合。以下示例演示了如何在 SmartConfig.xml 中声明 appSettings 配置节和自定义节,该自定义节使用 MyCongifSectionHandler 类。

 <configuration>
     
    <appSettings>
        <add key="Key 1" value="app Settings Value 1" />
        <add key="Key 2" value="app Settings Value 2" />
        <add key="Key 3" value="app Settings Value 3" />
    </appSettings>

    <configSections>
        
      <section name="mySection" 
       type="MySampleApplication.MyConfigSectionHandler,MySampleApplication" />
    </configSections>

 <mySection setting1="Value1" setting2="value two" setting3="third value" />
    
</configuration>

步骤 5:定义实现 IConfigSectionHandler 接口的配置节处理程序类。以下示例显示了在示例下载的演示项目中包含的 MyConfigSectionHandler 类的定义。

using System;
using System.Xml;
using SmartDeviceUtilities.ConfigurationManagement;

namespace MySampleApplication
{
    
    /// <summary>
    /// Sample configuration section handler
    /// </summary>
    public class MyConfigSectionHandler : IConfigSectionHandler
    {
        
        private string setting1;
        private string setting2;
        private string setting3;
        
        public MyConfigSectionHandler()
        {
        }

        public string Setting1
        {
            get
            {
                return setting1;
            }
            set
            {
                setting1 = value;
            }
        }

        public string Setting2
        {
            get
            {
                return setting2;
            }
            set
            {
                setting2 = value;
            }
        }

        public string Setting3
        {
            get
            {
                return setting3;
            }
            set
            {
                setting3 = value;
            }
        }

        #region IConfigSectionHandler Members

        /// <summary>
        /// "Create" method implementation
        /// </summary>
        /// <param name="sectionNode"></param>
        /// <returns></returns>
        public object Create(XmlNode sectionNode)
        {
            try
            {
                
                MyConfigSectionHandler myConfigSectionHandler= 
                                        new MyConfigSectionHandler();
                
                if (sectionNode == null)
                {
                    //Probably you could pickup the exception
                    // message from a resource file.
                    throw new ArgumentNullException("Configuration" +
                                       " section node cannot be null");
                }

                myConfigSectionHandler.Setting1  = 
                              sectionNode.Attributes["setting1"].Value;
                myConfigSectionHandler.Setting2  = 
                              sectionNode.Attributes["setting2"].Value;
                myConfigSectionHandler.Setting3  = 
                              sectionNode.Attributes["setting3"].Value;
                
                return (myConfigSectionHandler);
            }

            catch
            {
                throw;
            }

        }

        #endregion
    }
}

步骤 6:在应用程序中访问和使用 appSettings 配置信息。以下代码片段显示了如何访问 appSettings 配置节。

        /// <summary>
        /// Gets the appSettings
        /// </summary>
        private void GetAppSettings()
        {
            StringBuilder builder = new StringBuilder();
            NameValueCollection collection = ConfigurationSettings.AppSettings;

            foreach (String key in collection)
            {
                builder.Append(key);
                builder.Append(": ");
                builder.Append(collection[key]);
                builder.Append(", ");
            }
        
            //
            // TODO: Add the code that uses the configuration information here
            //
        }

步骤 7:在应用程序中访问和使用配置信息。以下代码片段显示了如何访问特定的配置节对象。

public void GetMyConfigSettings()
{
   MyConfigSectionHandler myConfigSectionHandler = 
     (MyConfigSectionHandler) ConfigurationSettings.GetConfig("mySection");

   String setting1 = myConfigSectionHandler.Setting1;
   String setting2 = myConfigSectionHandler.Setting2;
   String setting3 = myConfigSectionHandler.Setting3;


   //
   // TODO: Add the code that uses the configuration information here
   //

}

历史

  • 2004 年 4 月 5 日 - 初始版本。
  • 2004 年 4 月 9 日 - 更新 - 支持 appSettings 配置节。
© . All rights reserved.