添加自定义属性自定义提供配置节中的app.config [英] Adding custom attributes to Custom Provider Configuration Section in app.config

查看:1878
本文介绍了添加自定义属性自定义提供配置节中的app.config的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面上的如何创建一个.NET框架提供



基本上,这文章解释了大大如何使用配置文件中像结束以下内容:



<预类=郎咸平的XML prettyprint-覆盖> <结构>
< configSections>
<节名称=数据TYPE =DataProviderConfigurationSection/>
< / configSections>
<数据defaultProvider =MyDataProvider>
<供应商>
<添加名称=MydataProviderTYPE =MyDataProvider/>
< /供应商>
< /数据>
< /结构>



<添加/> 元素允许你定义一个人员。



不过,我想知道如何扩展添加与入门。自定义属性



例如:



<预类=郎咸平的XML prettyprint-覆盖> <供应商>
<添加名称=MydataProviderTYPE =MyDataProvidermyProperty的=myvalue的myProperty2 =myValue2... />
< /供应商>



任何帮助将不胜感激。


解决方案

下面是我终于找到了。这是关于实施提供者框架当元素与多个属性,以及如何延伸到处理这些非常具体的问题。有关自定义配置节的所有答案都行,但没有解决原来的问题。



如果您需要实现一个自定义的提供程序,如的MembershipProvider ,而是为你自己的目的,你需要详细阅读这篇文章:的创建自己的提供框架



这是极好的读数。现在,如果你需要的元素与自己的属性扩展,这里是你需要改变...



什么

1),接下来是在文章中讨论(有代码可能有一些调整):

 使用系统; 
使用System.Configuration;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用System.Configuration.Provider;
使用System.Collections.Specialized;


公共抽象类的DataProvider:的ProviderBase
{
//定义的方法,由提供商使用。这些都是自己的提供自定义方法。
公共抽象无效的get();
公共抽象无效删除();
}

公共类DataProviderCollection:ProviderCollection {}




//的名称通常是相同的抽象类,减去供应商的一部分。坚持我们的(假)的例子。我们就会有一个名为Data静态类。
公共静态类数据
{
私人静态布尔_isInitialized = FALSE;

私有静态的DataProvider _provider;
公共静态的DataProvider提供
{
得到
{
初始化();
返回_provider;
}
}

私有静态DataProviderCollection _providers;
公共静态DataProviderCollection提供商
{
得到
{
初始化();
返回_providers;
}
}

私有静态无效初始化()
{
DataProviderConfigurationSection dataConfig = NULL;

如果
{
//获取该功能的
dataConfig =(DataProviderConfigurationSection)ConfigurationManager.GetSection(数据)的配置部分(_isInitialized!);

如果(dataConfig == NULL)
{
抛出新ConfigurationErrorsException(数据未配置为与本申请中使用);
}

_providers =新DataProviderCollection();

//使用ProvidersHelper类每个供应商
ProvidersHelper.InstantiateProviders(dataConfig.Providers,_providers的typeof(的DataProvider))调用初始化();

//设置为默认提供
_provider参考= _providers [dataConfig.DefaultProvider]作为DataProvider的;

_isInitialized = TRUE;
}
}

公共静态无效的get()
{
初始化();
如果(_provider!= NULL)
{
_provider.Get();
}
}

公共静态无效删除(),
{
初始化();
如果(_provider!= NULL)
{
_provider.Delete();
}
}
}

公共类MyDataProvider:DataProvider的
{




酒店的公共覆盖无效的get()
{
//获取代码
}

公共覆盖无效删除(),
{
//删除代码
}
}

公共类DataProviderConfigurationSection:配置节
{
公共DataProviderConfigurationSection()
{
_defaultProvider =新的ConfigurationProperty(defaultProvider的typeof(串),NULL);
_providers =新的ConfigurationProperty(提供者的typeof(ProviderSettingsCollection),NULL);
_properties =新ConfigurationPropertyCollection();

_properties.Add(_providers);
_properties.Add(_defaultProvider);
}

私人只读的ConfigurationProperty _defaultProvider;
[的ConfigurationProperty(defaultProvider)]
公共字符串DefaultProvider
{
{返回(串)基地[_defaultProvider] }
集合{基地[_defaultProvider] =价值; }
}

私人只读的ConfigurationProperty _providers;
[的ConfigurationProperty(提供者)]
公共ProviderSettingsCollection提供商
{
{返回(ProviderSettingsCollection)基地[_providers] }
}

私人ConfigurationPropertyCollection _properties;
保护覆盖ConfigurationPropertyCollection属性
{
{返回_properties; }
}
}

公共静态类ProvidersHelper
{
私有静态类型providerBaseType = typeof运算(的ProviderBase);

///<总结>
///实例化供应商。
///< /总结>
///< PARAM NAME =providerSettings>在设置< /参数>
///< PARAM NAME =providerType>该供应商的类型被实例化< /参数>
///<&回报GT;< /回报>
公共静态的ProviderBase InstantiateProvider(ProviderSettings providerSettings,类型providerType)
{
的ProviderBase BASE2 = NULL;

{
字符串str =(providerSettings.Type == NULL)?空:providerSettings.Type.Trim();
如果(string.IsNullOrEmpty(STR))
{
抛出新的ArgumentException(提供程序类型名称是无效的);
}
型C = Type.GetType(STR,真实,真实); (!providerType.IsAssignableFrom(C))
如果
{
抛出新的ArgumentException(的String.Format(供应商必须实现类型{0},providerType.ToString()));
}
BASE2 =(的ProviderBase)Activator.CreateInstance(C);
的NameValueCollection参数= providerSettings.Parameters;
NameValueCollection中配置=新的NameValueCollection(parameters.Count,StringComparer.Ordinal);
的foreach(在参数字符串STR2)
{
配置[STR2赛车] =参数[STR2]
}
base2.Initialize(providerSettings.Name,配置);
}
赶上(例外的例外)
{
如果(例外是ConfigurationException的)
{
扔;
}
抛出新ConfigurationErrorsException(exception.Message,
providerSettings.ElementInformation.Properties [型。来源,
providerSettings.ElementInformation.Properties [型。LINENUMBER );
}
返回BASE2;
}

公共静态无效InstantiateProviders(ProviderSettingsCollection providerSettings,ProviderCollection商,型号类型)
{
的foreach(在providerSettings ProviderSettings设置)
{
providers.Add(ProvidersHelper.InstantiateProvider(设置类型));
}
}
}



2)这是配置你使用上面的代码文件:

 <结构> 
< configSections>
<节名称=数据TYPE =DataProviderConfigurationSection/>
< / configSections>
<数据defaultProvider =MyDataProvider>
<供应商>
<添加名称=MydataProviderTYPE =MyDataProvider/>
< /供应商>
< /数据>
< /结构>



3)现在,这里是你需要为了使用读取属性修改什么<添加>在配置文件中元素

 公共抽象类的DataProvider :的ProviderBase 
{

公共字符串MyAttribute1 {搞定;组; }
公共字符串MyAttribute2 {搞定;组; }
公共字符串MyAttribute3 {搞定;组; }

//定义要由提供者所使用的方法。这些都是自己的提供自定义方法。
公共抽象无效的get();
公共抽象无效删除();

公共覆盖无效初始化(字符串名称,NameValueCollection中配置)
{

MyAttribute1 =配置[MyAttribute1];
MyAttribute2 =配置[MyAttribute2];
MyAttribute3 =配置[MyAttribute3];

base.Initialize(名称,配置);
}
}



4)配置文件看起来是这样的:

 <结构> 
< configSections>
<节名称=数据TYPE =DataProviderConfigurationSection/>
< / configSections>
<数据defaultProvider =MyDataProvider>
<供应商>
<添加名称=MydataProviderTYPE =MyDataProviderMyAttribute1 =MyValue1MyAttribute2 =MyValue2/>
< /供应商>
< /数据>
< /结构>



作为奖励,这里是一个单元测试来验证它的工作原理:

  [TestMethod的] 
公共无效RunMyDataProviderTest()
{
的DataProvider的dataProvider = Data.Provider;

Assert.IsInstanceOfType(dataProvider中的typeof(MyDataProvider));

Assert.AreEqual(dataProvider.MyAttribute1MyValue1);
Assert.AreEqual(dataProvider.MyAttribute2MyValue2);
}


I am following this great article on how to create a Provider framework in .NET

Basically, this article explains greatly how to end up with a configuration file like the following:

   <configuration>
     <configSections>
        <section name="data" type="DataProviderConfigurationSection" />
      </configSections>
      <data defaultProvider="MyDataProvider">
         <providers>
            <add name="MydataProvider" type="MyDataProvider"  />
         </providers>
      </data>
   </configuration>

Where the <add/> element allows you to define a provider.

However, I would like to know how to extend the add entry with custom attributes.

For example:

<providers>
  <add name="MydataProvider" type="MyDataProvider" myProperty="myValue" myProperty2="myValue2" ... />
</providers>

Any help will be greatly appreciated.

解决方案

Here is what I finally found. This is a very specific question about extending the element with more attributes and how to handle them when implementing a Provider Framework. All the answers about custom configuration sections are OK but not addressing the original question.

If you need to implement a custom Provider, like the MembershipProvider, but for your own purpose, you need to definitely read this article: Creating Your Own Provider Framework

It is excellent reading. Now if you need to extend the element with your own attributes, here is what you need to change...

1) Next is the code discussed in the article (There might be some adaptations):

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration.Provider;
using System.Collections.Specialized;


    public abstract class DataProvider : ProviderBase
    {
        // Define the methods to be used by the provider.  These are custom methods to your own provider.
        public abstract void Get();
        public abstract void Delete();
    }

    public class DataProviderCollection : ProviderCollection { }




    //The name is typically the same as the abstract class, minus the Provider part. Sticking to our (fake) example. we'd have a static class called Data.
    public static class Data
    {
        private static bool _isInitialized = false;

        private static DataProvider _provider;
        public static DataProvider Provider
        {
            get
            {
                Initialize();
                return _provider;
            }
        }

        private static DataProviderCollection _providers;
        public static DataProviderCollection Providers
        {
            get
            {
                Initialize();
                return _providers;
            }
        }

        private static void Initialize()
        {
            DataProviderConfigurationSection dataConfig = null;

            if (!_isInitialized)
            {
                // get the configuration section for the feature
                dataConfig = (DataProviderConfigurationSection)ConfigurationManager.GetSection("data");

                if (dataConfig == null)
                {
                    throw new ConfigurationErrorsException("Data is not configured to be used with this application");
                }

                _providers = new DataProviderCollection();

                // use the ProvidersHelper class to call Initialize() on each provider
                ProvidersHelper.InstantiateProviders(dataConfig.Providers, _providers, typeof(DataProvider));

                // set a reference to the default provider
                _provider = _providers[dataConfig.DefaultProvider] as DataProvider;

                _isInitialized = true;
            }
        }

        public static void Get()
        {
            Initialize();
            if (_provider != null)
            {
                _provider.Get();
            }
        }

        public static void Delete()
        {
            Initialize();
            if (_provider != null)
            {
                _provider.Delete();
            }
        }
    }

    public class MyDataProvider : DataProvider
    {




        public override void Get()
        {
            // Get Code
        }

        public override void Delete()
        {
            // Delete Code
        }
    }

    public class DataProviderConfigurationSection : ConfigurationSection
    {
        public DataProviderConfigurationSection()
        {
            _defaultProvider = new ConfigurationProperty("defaultProvider", typeof(string), null);
            _providers = new ConfigurationProperty("providers", typeof(ProviderSettingsCollection), null);
            _properties = new ConfigurationPropertyCollection();

            _properties.Add(_providers);
            _properties.Add(_defaultProvider);
        }

        private readonly ConfigurationProperty _defaultProvider;
        [ConfigurationProperty("defaultProvider")]
        public string DefaultProvider
        {
            get { return (string)base[_defaultProvider]; }
            set { base[_defaultProvider] = value; }
        }

        private readonly ConfigurationProperty _providers;
        [ConfigurationProperty("providers")]
        public ProviderSettingsCollection Providers
        {
            get { return (ProviderSettingsCollection)base[_providers]; }
        }

        private ConfigurationPropertyCollection _properties;
        protected override ConfigurationPropertyCollection Properties
        {
            get { return _properties; }
        }
    }

    public static class ProvidersHelper
    {
        private static Type providerBaseType = typeof(ProviderBase);

        /// <summary>
        /// Instantiates the provider.
        /// </summary>
        /// <param name="providerSettings">The settings.</param>
        /// <param name="providerType">Type of the provider to be instantiated.</param>
        /// <returns></returns>
        public static ProviderBase InstantiateProvider(ProviderSettings providerSettings, Type providerType)
        {
            ProviderBase base2 = null;
            try
            {
                string str = (providerSettings.Type == null) ? null : providerSettings.Type.Trim();
                if (string.IsNullOrEmpty(str))
                {
                    throw new ArgumentException("Provider type name is invalid");
                }
                Type c = Type.GetType(str, true, true);
                if (!providerType.IsAssignableFrom(c))
                {
                    throw new ArgumentException(String.Format("Provider must implement type {0}.", providerType.ToString()));
                }
                base2 = (ProviderBase)Activator.CreateInstance(c);
                NameValueCollection parameters = providerSettings.Parameters;
                NameValueCollection config = new NameValueCollection(parameters.Count, StringComparer.Ordinal);
                foreach (string str2 in parameters)
                {
                    config[str2] = parameters[str2];
                }
                base2.Initialize(providerSettings.Name, config);
            }
            catch (Exception exception)
            {
                if (exception is ConfigurationException)
                {
                    throw;
                }
                throw new ConfigurationErrorsException(exception.Message,
                    providerSettings.ElementInformation.Properties["type"].Source,
                    providerSettings.ElementInformation.Properties["type"].LineNumber);
            }
            return base2;
        }

        public static void InstantiateProviders(ProviderSettingsCollection providerSettings, ProviderCollection providers, Type type)
        {
            foreach (ProviderSettings settings in providerSettings)
            {
                providers.Add(ProvidersHelper.InstantiateProvider(settings, type));
            }
        }
    }

2) This is the config file that you use for the above code:

  <configuration>
    <configSections>
      <section name="data" type="DataProviderConfigurationSection" />
    </configSections>
    <data defaultProvider="MyDataProvider">
      <providers>
        <add name="MydataProvider" type="MyDataProvider"  />
      </providers>
    </data>
  </configuration>

3) Now, here is what you need to modify in order to use read the attributes in the <add> element in the configuration file.

    public abstract class DataProvider : ProviderBase
    {

        public string MyAttribute1 { get; set; }
        public string MyAttribute2 { get; set; }
        public string MyAttribute3 { get; set; }

        // Define the methods to be used by the provider.  These are custom methods to your own provider.
        public abstract void Get();
        public abstract void Delete();

        public override void Initialize(string name, NameValueCollection config)
        {

            MyAttribute1 = config["MyAttribute1"];
            MyAttribute2 = config["MyAttribute2"];
            MyAttribute3 = config["MyAttribute3"];

            base.Initialize(name, config);
        }
    }

4) The configuration file looks like this:

  <configuration>
    <configSections>
      <section name="data" type="DataProviderConfigurationSection" />
    </configSections>
    <data defaultProvider="MyDataProvider">
      <providers>
        <add name="MydataProvider" type="MyDataProvider" MyAttribute1="MyValue1" MyAttribute2="MyValue2"   />
      </providers>
    </data>
  </configuration>

And as a bonus, here is a Unit test to validate it works:

[TestMethod]
public void RunMyDataProviderTest()
        {
            DataProvider dataProvider = Data.Provider;

            Assert.IsInstanceOfType(dataProvider, typeof(MyDataProvider));

            Assert.AreEqual(dataProvider.MyAttribute1, "MyValue1");
            Assert.AreEqual(dataProvider.MyAttribute2, "MyValue2");
}

这篇关于添加自定义属性自定义提供配置节中的app.config的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆