Download ProviderPattern.zip

Introduction

Provider pattern allows the developers to create pluggable components. It was first introduced in framework 2.0 and it has lot of features like "Membership Provider", "Roles Provider" etc. and instantiates using configuration file.

This article provides guidelines to create logging component using provider pattern. The sample project contains two providers "TextLogProvider" and "XmlLogProvider" You can set one of them default in configuration file.

Base Data Provider Class

First of all you need to define abstract representation of all your methods. Create your data provider base class and your class must inherit from System.Configuration.Provider.ProviderBase base class.

Hide   Copy Code

public
abstract
class LogProviderBase : ProviderBase

{

   .


public
abstract
void WriteLog(LogType logType, string message);

   .

}

As you see LogProviderBase is an abstract class and it has abstract method WriteLog(..). In this example we have only one abstract method. But we can have more than one as per requirement.

Data Provider Class

After creating your base provider class, now you can create your concrete provider classes. In this sample I will create two providers for logging one for text and second for xml. Derive concrete provider class from LogProviderBase class and implement the abstract methods.

Hide   Shrink    Copy Code

public
class TextLogProvider : LogProviderBase

{

 


#region Data Members

 


private
string _filePath = "";

 


#endregion

 


#region Overrided Methods

 


public
override
void SetParameters(System.Collections.Specialized.NameValueCollection config)

   {

       _filePath = config["fileLocation"];

   }

 


public
override
void WriteLog(LogType logType, string message)

   {


var dir = Path.GetDirectoryName(_filePath);


if (!Directory.Exists(dir))

           Directory.CreateDirectory(dir);

 


using (var sw = new StreamWriter(_filePath, true))

       {


string s = string.Format("{0}, {1}, {2}", DateTime.Now, logType.ToString(), message);

           sw.WriteLine(s);

       }

   }

 


#endregion

 

}

Write the logging logic according to your provider type by implementing WriteLog(…). In TextLogProviderclass i am saving CVS line in text file.

Provider Collection & Configuration Section

For taking care of the provider configuration, you must write your own provider collection class derived from System.Configuration.ProviderCollection class. ProviderCollection class exposes properties and methods to work with the list of various data providers declared in your configuration file.

Hide   Copy Code

public
class LogProviderCollection : ProviderCollection

{


new
public LogProviderBase this[string name]

   {


get { return (LogProviderBase)base[name]; }

   }

}

Provider pattern reads the concrete providers from the configuration file, for this purpose you need one more class which will read all the provider collections from the configuration file. Create ProviderConfiguration class derived from the System.Configuration.ConfigurationSection file.

Hide   Copy Code

public
class LogProviderConfiguration : ConfigurationSection

{

 

   [ConfigurationProperty("providers")]


public ProviderSettingsCollection Providers

   {


get

       {


return (ProviderSettingsCollection)base["providers"];

       }

   }

 

   [ConfigurationProperty("default", DefaultValue = "XmlProvider")]


public
string DefaultProviderName

   {


get

       {


return
base["default"] as
string;

       }

   }

 

}

In this class you can add as many properties based on the different parameters that you need to extract from the configuration sections. All the properties must be decorated with the ConfigurationProperty attribute.

Configuration

For configuring the provider model, we need to define our provider configuration section in <configsections>. Here we can add a <section> element with the name of the provider model configuration section element and the type of our data provider configuration class.

After configuring section (we configured LogProviders as section name). Now we need to add our all available providers in it and set one default provider from them.

Hide   Copy Code

<configSections>


<section
name="LogProviders"


type="ProviderPatternLogTest.LogProvider.LogProviderConfiguration, ProviderPatternLogTest"/>

</configSections>

 

 

<LogProviders
default="XmlProvider">


<providers>

 


<add
name="XmlProvider"


type="ProviderPatternLogTest.LogProvider.Providers.XmlLogProvider, ProviderPatternLogTest"


fileLocation="c:\temp\log.xml"/>

 


<add
name="TextProvider"


type="ProviderPatternLogTest.LogProvider.Providers.TextLogProvider, ProviderPatternLogTest"


fileLocation="c:\temp\log.txt"/>

 


</providers>

</LogProviders>

Use Provider Model in Code

It is very easy to use provider model in your code, simply get the default property of Provider Manager Class and then call your concrete methods

Hide   Copy Code

LogProviderManager.Default.WriteLog(logType, txtMessage.Text);

Get Other Information

You can also easily get other useful information of your concrete provider. Simply get ProviderSetting using LogProviderManager.

Hide   Copy Code

var setting = LogProviderManager.ProviderSettings[defaultName];

 

var setStr = GetSetting(setting);

 

MessageBox.Show(setStr);

GetSetting(...) method only parse all the parameters and returns concatenated string message.

Hide   Copy Code

private
string GetSetting(ProviderSettings setting)

{

   StringBuilder str = new StringBuilder();

   str.AppendLine(string.Format("Default Provider name: {0}", setting.Name));

   str.AppendLine(string.Format("Default Provider type: {0}", setting.Type));

   str.AppendLine("------------------Parameters--------------------");


foreach (String s in setting.Parameters)

   {

 

       str.AppendLine(string.Format("Parameter: {0} -> {1}", s, setting.Parameters.Get(s)));

   }

   str.AppendLine("---------------------------------------");

   str.AppendLine("");

 


return str.ToString();

}

 

From: https://www.codeproject.com/Articles/550495/Provider-Pattern-for-Beginners

最新文章

  1. 2013 duilib入门简明教程 -- 部分bug (11)
  2. 利用Maven把项目生成jar包供其他项目使用
  3. Python 基礎 - 列表的使用_v2
  4. moogodb3.x总结
  5. Google Analytics统计代码GA.JS中文教程
  6. SELinux入门
  7. intellij idea 注释行如何自动缩进?
  8. ViewConfiguration滑动参数设置类
  9. COJ 0995 WZJ的数据结构(负五)区间操作
  10. AsyncTask总结(经典,附带源码)
  11. Oracle表介绍--簇表
  12. 用Eclipse 搭建一个Maven Spring SpringMVC 项目
  13. Java中的Iterable与Iterator详解
  14. Java新知识系列 四
  15. Linux搭建bugfree
  16. tensorflow模型量化
  17. Hadoop概念学习系列之Hadoop、Spark学习路线(很值得推荐)(十八)
  18. 概率校准Probability Calibration
  19. STL应用之set
  20. Git之hotfix热修复分支

热门文章

  1. SQL Server、Oracle和MySQL中查出值为NULL的替换
  2. linux 内核升级2 转
  3. javascript 编辑网页
  4. Revit API修改保温层厚度
  5. In-Place upgrade to Team Foundation Server (TFS) 2015 from TFS 2013Team Foundation Server TFS TFS 2015 TFS upgrade TFS with Sharepoint
  6. VC 中 编译 boost 1.34.1 或者 1.34.0
  7. 委托、Lambda表达式、事件系列02,什么时候该用委托
  8. quartz 2.0 与1.0功能对比
  9. WordPress主题开发:style.css主题信息标记
  10. javax.servlet不存在问题的解决