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

Provider Pattern for Beginners in .net的更多相关文章

  1. 二十四种设计模式:提供者模式(Provider Pattern)

    提供者模式(Provider Pattern) 介绍为一个API进行定义和实现的分离.示例有一个Message实体类,对它的操作有Insert()和Get()方法,持久化数据在SqlServer数据库 ...

  2. Provider Pattern提供者模式和策略模式

    http://www.codeproject.com/Articles/18222/Provider-Pattern Introduction Provider pattern is one of t ...

  3. 乐在其中设计模式(C#) - 提供者模式(Provider Pattern)

    原文:乐在其中设计模式(C#) - 提供者模式(Provider Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 提供者模式(Provider Pattern) 作者:weba ...

  4. 打造属于你的提供者(Provider = Strategy + Factory Method) 设计模式 - Provider Pattern(提供者模式)

    打造属于你的提供者(Provider = Strategy + Factory Method)   1.1.1 摘要 在日常系统设计中,我们也许听说过提供者模式,甚至几乎每天都在使用它,在.NET F ...

  5. Membership三步曲之进阶篇 - 深入剖析Provider Model

    Membership 三步曲之进阶篇 - 深入剖析Provider Model 本文的目标是让每一个人都知道Provider Model 是什么,并且能灵活的在自己的项目中使用它. Membershi ...

  6. 深入剖析Provider Model

    Membership三步曲之进阶篇 - 深入剖析Provider Model Membership 三步曲之进阶篇 - 深入剖析Provider Model 本文的目标是让每一个人都知道Provide ...

  7. [React] Implement a React Context Provider

    If you have state that needs to exist throughout your application, then you may find yourself passin ...

  8. Code Project精彩系列(转)

    Code Project精彩系列(转)   Code Project精彩系列(转)   Applications Crafting a C# forms Editor From scratch htt ...

  9. 抽象工厂在ADO.Net中的应用

    https://msdn.microsoft.com/zh-cn/library/ms971499.aspx http://www.c-sharpcorner.com/UploadFile/moses ...

随机推荐

  1. Linux进程管理工具 Supervisord 的安装 及 入门教程

    Supervisor是一个进程管理工具,官方的说法: 用途就是有一个进程需要每时每刻不断的跑,但是这个进程又有可能由于各种原因有可能中断.当进程中断的时候我希望能自动重新启动它,此时,我就需要使用到了 ...

  2. JAVA 对象序列化(二)——Externalizable

    Java默认的序列化机制非常简单,而且序列化后的对象不需要再次调用构造器重新生成,但是在实际中,我们可以会希望对象的某一部分不需要被序列化,或者说一个对象被还原之后,其内部的某些子对象需要重新创建,从 ...

  3. SVN的管理方式和git的管理方式

    SVN是集中式的管理方式.大致流程如下: 1.从服务器上将整个项目代码检出到本地电脑硬盘中(一般来说,是从主分支上下载的代码).2.然后在svn服务器中建立新的开发分支,将硬盘中的代码提交到该开发分支 ...

  4. 从Web Service和Remoting Service引出WCF服务

    本篇先通过Web Service和Remoting Service创建服务,抛砖引玉,再体验WCF服务.首先一些基本面: 什么是WCF? Windows Communication Foundatio ...

  5. SQLCE使用本地数据库优化

    一.数据绑定 1.使用数据虚拟化和SKIP/TAKE 使用 Skip 和 Take 方法可确保直到需要在 ListBox 控件中显示数据时才将数据库中的数据加载到内存中. 例如,以下代码显示了如何从数 ...

  6. Eclipse 离线汉化的方法

    本文感谢:http://jingyan.baidu.com/article/e75057f28401a8ebc91a899e.html 首先进入网址:http://www.eclipse.org/ba ...

  7. .Net Core中文编码问题整理

    1..Net Core Console控制台程序 在.Net Core中默认System.Text中不支持CodePagesEncodingProvider.Instance, System.Text ...

  8. ADB与AVD的常见问题

    一.adb问题常用解决方法 若是模拟器启动正常,但是adb检测不到模拟器,我们给他一套不解释连招,下面教大家几招基础拳法. 1.基础拳法一:循环自动检测 下图那个小按钮,点它,狠狠的点它,然后点运行, ...

  9. Sql Server简单加密与解密 【转】

    前言: 在SQL Server 2005和SQL Server 2008之前.如果希望加密敏感数据,如财务信息.工资或身份证号,必须借助外部应用程序或算法.SQL Server 2005引入内建数据加 ...

  10. Linear Regression总结

    转自:http://blog.csdn.net/dongtingzhizi/article/details/16884215 Linear Regression总结 作者:洞庭之子 微博:洞庭之子-B ...