Provider Model and Configuration Sections
Provider Design Pattern, Part 2 (Rob Howard)
The Last Configuration Section Handler I'll Ever Need
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
namespace TemplatedSampleSite.ProviderPattern
{
public class IPLConfig
{
private string _path;
private string[] _mass = new string[]{"a","b"};
public string Path
{
get
{
return _path;
}
set
{
_path = value;
}
}
}
public class IPLocalizer
{
public static string GetCultureCode(string ip)
{
return IPLocalizerProvider.Instance().GetCultureCode(ip);
}
}
public abstract class IPLocalizerProvider : ProviderBase
{
public abstract string GetCultureCode (string ip);
// static private Hashtable providers = new Hashtable();
static private IPLocalizerProvider _instance;
public static IPLocalizerProvider Instance()
{
IPLocalizerProvider prov =_instance;
//providers[config.Path] as SqlIPLocalizerProvider;
if(prov==null)
{
IPLConfig config = (IPLConfig)System.Configuration.ConfigurationSettings.GetConfig("providers/IPLConfig");
prov = new SqlIPLocalizerProvider(config.Path) as IPLocalizerProvider;
//providers[config.Path] = prov;
_instance = prov;
}
return prov;
}
}
public abstract class ProviderBase
{
//public abstract void Initialize (string name,NameValueCollection configValue);
public abstract string Name { get; }
}
public class SqlIPLocalizerProvider : IPLocalizerProvider
{
private string _path;
public SqlIPLocalizerProvider(string path):base()
{
_path=path;
}
public override string GetCultureCode (string ip)
{
return "SqlMembershipProvider checked ip:" + ip + ",Path= " + _path;
}
// Provider base methods & properties
// public override void Initialize (string name,NameValueCollection configValue )
// {
//
// }
public override string Name
{
get
{
return "SqlMembershipProvider";
}
}
}
public class XmlSerializerSectionHandler :
IConfigurationSectionHandler
{
//DevelopMentor.Candera.Utilities.XmlSerializerSectionHandler
public object Create(
object parent,
object configContext ,
System.Xml.XmlNode section)
{
XPathNavigator nav = section.CreateNavigator ();
string typename = ( string ) nav.Evaluate ("string(@type)");
Type t = Type.GetType ( typename );
XmlSerializer ser = new XmlSerializer (t);
return ser.Deserialize ( new XmlNodeReader (section));
}
}
}