Pages

Showing posts with label Architecture and Design Pattern. Show all posts
Showing posts with label Architecture and Design Pattern. Show all posts

Sunday, August 12, 2012

SharePoint: Too much customization is not good for health

SharePoint allows developer/architect to customize it’s power in numerous ways. You can write event receivers, timer jobs, webparts, application pages and so on. But what I’ve found with my years of experience in working with SharePoint is that sometimes developers/architects make too much customization which is not good from maintenance point of view.

If you are senior SharePoint developer or architect or you have the responsibility to design a solution for SharePoint, first focus on out-of-the-box way to solve the problems. If possible, try to compromise features talking to clients.

Real world Example

Let’s consider a simple example. You have a database which is used by other LOB systems. SharePoint reads and writes data to the database and then other LOB systems (like SAP or some custom applications) use (only read) the data in the database for it’s own use.

image

Now client requirement is to show the data in the database as SharePoint list so that clients get the feelings that the tables in the database are kind of List in the SharePoint. Now what options do you have? I think we have two options:

  • Option 1: Use Business Connectivity Service to show Database tables as SharePoint list
  • Option 2: Create custom SharePoint list and then write event receivers to synchronize data between database and List.

Different architect/developer under different circumstances, may use first option or second. But the first option is more out-of-the-box way of implementing the requirements. However some situations demand the second option where you need to  write custom code and need to sync data between SharePoint list and table in database manually. So as an architect/developer I would prefer the first option using Business Connectivity Service. If I need to choose second option then I should have explanation why I need to use second option. The explanation might be Business Connectivity Service has some limitations that we need to overcome with second option, or the requirements are too complex to implement with Business Connectivity Service.

 

But Why?

Now you may ask why it’s matter if I do more customization (I would prefer to say unnecessary customization). I bet it’s matter. The more customization you do, the more difficult to manage codebase, more time to develop, more possible to generate more bugs, more difficult to upgrade to newer version of SharePoint and many more. SharePoint is a rich application framework and we need to utilize it in best possible ways.

 

conclusion

The idea I wanted to share here not to say that you should not do any customization rather make sure your customization really needed. If you do unnecessary customization then you might paving the way for more customizations (maybe for error fixing or features related to customizations). As I read somewhere, “A single bad developer creates job for more developers”. Let’s not create more customizations by an unnecessary customizations.

Friday, March 9, 2012

Managing a single codebase for both SharePoint 2007 and 2010

Sometimes we need to work on source code that needs to be maintained for both SharePoint 2007 and 2010. There’s no built-in support from Microsoft to manage two versions of same Visual Studio solution for multiple versions of SharePoint. The problem is more complicated as the SharePoint assembly details are hard-coded in markup (ascx, aspx).

Anyway, I worked on a project where my team was developing a SharePoint custom product and some of our clients are still using SharePoint 2007 while some others are already moved to SharePoint 2010. So we had a challenge to support all clients (both SharePoint 2007 and 2010) but maintaining a single codebase. I am not demanding that the solution I’ll provide in this post is the best but the approach might be helpful to minimize code duplication. The sample Visual studio project can be download from skydrive.

 

Introduction

I’ve used Model View Presenter (MVP) to separate the presenter logic from view. Also, code that not dependent on SharePoint assembly directly are put in presenter layer. If for any reason, presenter is dependent on SharePoint assembly (for example SPGridView is used in code-behind) then the SharePoint assembly dependent code is implemented in individual (2007 or 2010) SharePoint project where common non-SharePoint presenter logic is kept in Presenter layer. For explaining the solution, I would like to introduce you to the Visual Studio projects (can be downloaded from here)I’ve been used.

  • Sohel.Blogging.Common: This is common project where interfaces, data contracts, common utilities etc are declared.
  • Sohel.Blogging.Presenter: This is the presenter layer where all non-SharePoint related presenter logic is kept. Since there’s no SharePoint-dependent logic is places, no reference to SharePoint dll is needed. As a result this project (or more specifically, presenter logic) can be reused by both SharePoint 2007 and 2010.
  • Sohel.Blogging.Wss: This is SharePoint 2007 (wss) project from where we’ll generate WSP file. Only SharePoint 2007 project structure, Views (aspx, ascx etc.) and Site artifacts (site definition, columns etc.) are placed in this project. As code-behind is replaced by presenter (which resides in Presenter layer), only views are need to duplicated between SharePoint 2007 and 2010.
  • Sohel.Blogging.Foundation: This is SharePoint 2010 project from which we’ll generate WSP solution file. Only views (aspx, ascx), site structure and site artifacts (site definitions, site columns etc.) are maintained in this project

To plug presenter/view to each other, Dependency Injection is used and for that purpose, Microsoft Patterns & Practices SharePoint Guidance is used. The Guidance Library for both SharePoint 2007 and 2010 can be downloaded from CodePlex (http://spg.codeplex.com/). For more information on how to use the Guidance Library for Dependency Injection please follow another post SharePoint Service Locator in my blog.

The overall architecture of the Visual Studio solution is presented below:

image

Figure 1: Visual Studio Project Dependency

The overall goal of the architecture is to move aspx/ascx code behind to presenter layer. As a result the code-behind logic is reused in two different views (SharePoint 2007 and 2010).

 

Views

The view (aspx, ascx) files are slimmed by removing code to presenter. View files (aspx,ascx etc) are placed in Sohel.Blogging.Foundation or Sohel.BLogging.Wss project. An interface is extracted from view to make Controls (like TextBox, Dropdown etc) available to Presenter. This is done by exposing View’s controls as the interface properties of the view. Though this is not the real Model View Presenter (MVP) but it works and faster to develop. The only problem is that the view interface/presenter is tightly coupled to asp.net controls.

public interface IProductListview
{
    Panel CreateListPanel { get; }
    Panel AddItemListPanel { get; }
    HtmlGenericControl MessageDiv { get; }
    HyperLink ViewAllProductLink { get; }
    Product GetProduct();
    string GetProductListUrl();
}

However if you use SharePoint controls (like SPGridView), then instead of exposing them in View interface, keep the logic related to the control in View and use a method in view. For example if you use SharePoint DateTime control, a method in view/code-behind can be used to put the logic related to SharePoint control. The following view interface declares SetDate method that set the date value of SharePoint DateTime control.

public interface IProductListview
{
    //Panel CreateListPanel { get; }
    //Panel AddItemListPanel { get; }
    //HtmlGenericControl MessageDiv { get; }
    //HyperLink ViewAllProductLink { get; }
    //Product GetProduct();
    //string GetProductListUrl();
    void SetDate(DateTime dateTime);
}

The view (say UserControl) below implement the SetDate method.

public partial class ProductList : UserControl, IProductListview
{
    public void SetDate(DateTime dateTime)
    {
        uiSpDateTimePicker.SelectedDate = dateTime;
    }
..............
..............
}

 

Presenter

All Presenters are kept in Sohel.Blogging.Prensenter project. Presenter access View controls through view interface. As I’ve mentioned already, this is not the right for MVP pattern to use web control directly inside view interface. SharePoint Service Locator is used as shown below:

public class CurrentSharePointServiceLocator : IBloggingServiceLocator
{
    public T ResolveInstance<T>()
    {
        return SharePointServiceLocator.Current.GetInstance<T>();
    }
}

The interface to the service locator (IBloggingServiceLocator) is passed to the Presenter constructor inside view, as shown below:

public partial class ProductList : UserControl, IProductListview
{
    private ProductListPresenter _presenter;
    public ProductListPresenter Presenter
    {
        get
        {
            if (_presenter == null)
            {
                _presenter = new ProductListPresenter(this, CurrentSharePointServiceLocator.GetInstance<IBloggingServiceLocator>());
            }
            return _presenter;
        }
    }
.....
.....
}

As presenter get access to the IBloggingServiceLocator, presenter can access any object that is registered through service locator. The presenter gets access to the view and service locator through constructor as shown below:

public class ProductListPresenter:APresenter
{
    public IProductListview View { get; set; }

    public ProductListPresenter(IProductListview view,IBloggingServiceLocator serviceLocator):base(serviceLocator)
    {
        View = view;
    }
.....
.....
}

 

New development Consideration

Once the project architecture is in place and if you need to develop new control, application pages etc, you should develop new control for any version of SharePoint first. For example if I need to develop a new application page, I would go and develop the page for SharePoint 2010. Then I would refactor the code to move the code-behind logic to Presenter class. Then I’ll create a new page in SharePoint 2007 copying the similar file from SharePoint 2010 (but surely with modifications). Now while you’ll create new page for SharePoint 2007, you may fine more refactoring needed to generalize code more for both SharePoint 2007 and 2010. The only duplication needs to be made in this approach is resources like markup/xml/css/jss etc. need to be duplication. But I think its possible to minimize the duplication by putting most of the resources in separate web project and on post-build event, you can copy the resources in individual SharePoint projects.

 

Conclusion

As more and more clients are adopting SharePoint and more and more Independent Software Vendor (ISV) are developing custom SharePoint products, ISVs need to support more than one version of their product. Since Microsoft doesn’t provide any out-of-the box solution for this multiple-version support for Visual Studio Solution, it takes extra efforts for developers to use the same codebase for different version of SharePoint and increase the possible of code duplication which in turn make maintenance difficult. You can download the sample code from skydrive.

Disclaimer: The solution provided in this post is not the best solution but a workaround. If anybody has any better idea, you are welcome to share.

Monday, January 11, 2010

Common Service Locator: Separate hard reference of your IoC/DI container from your solution

Service Locator

Dependency Injection is an way to separate dependency. Someone can use Constructor Injection, Setter Injection etc for injecting dependency. Service Locator solves the same problem as Dependency Injector but it uses different approach. Service Locator holds reference of all types/objects an application needs. So whenever you need to use an instance of a type/class, ask service locator to provide the instance. Simply, the Service Locator uses a container to hold all references to class/type to instance/object mapping. You can follow the links for details:

Why Common Service Locator?

Nowadays as a .NET developer, we have a set of DI/IoC containers to choose from. We have option for Spring.NET, Unity Application Block, Castle Windsor etc. Whenever you use any of them in your project, the project is tightly coupled with that container. So if you start your project with Spring.Net Container then your project will be tightly coupled with the Spring.Net container. But later if your decide to use Unity Application Block then can you imagine how much hassles are waiting for you? You need to remove all reference of Spring.Net container from your code. Another example might be, you are developing a library that will be used by other users. Now if you use a IoC Container (say Spring.Net) then you are forcing users to use Spring.Net whenever they want to use the library. So if it would be possible to loose the coupling between your code and the IoC container then you can easily remove dependencies on IoC container.The Common Service Locator project at codeplex is aimed to attain the goal.

Use Common Service Locator

1. Get an understanding of IServiceLocator interface
The Start with an Interface IServiceLocator which has few methods which is generic to any IoC container.The IServiceLocator inherits from IServiceProvider.
public interface IServiceProvider
{
    object GetService(Type serviceType);
}
 
public interface IServiceLocator : IServiceProvider
{
    object GetInstance(Type serviceType);
    object GetInstance(Type serviceType, string key);
    IEnumerable<object> GetAllInstances(Type serviceType);
    TService GetInstance<TService>();
    TService GetInstance<TService>(string key);
    IEnumerable<TService> GetAllInstances<TService>();
}
The Common service Locator will implement the interface IServiceLocator. The Common Service Locator framework has provided an abstract implementation of IServiceLocator called ServiceLocatorImplBase. The ServiceLocatorImplBase has two abstract methods which actually depends on IoC Container.
  • DoGetAllInstances: get all instance of a particular type from Container.
  • DoGetInstance: Get a particular instance from Container
For getting instance from container, ServiceLocatorImplBase uses above two methods. And those two methods are implemented by derived class. And Container is actually needed by those two methods. So Container is specific to individual implementation.
2. Develop your custom Service Locator
I have developed two service Locators for Unity and Spring.Net. UnityServiceLocator can use Unity container whereas Spring.Net can uses Object Factory. The following class diagram shows two implementations that I have developed in the project attached with this post.
image
Figure: Two sample implementations of Common Service Locator
3. Develop BootStrapper
So I have developed two service locators till now. Now I need to develop two bootstrappers for Spring.Net and Unity as type registration are different for two.
public abstract class CommonBootStrapper
{
    public static IServiceLocator Locator;
 
    protected CommonBootStrapper()
    {
        Locator = CreateServiceLocator();            
    }
 
    protected abstract IServiceLocator CreateServiceLocator();
}
The common bootstrapper has a instance of IServiceLocator which means it can hold reference to any class’s instance inheriting from ServiceLocatorImplBase (as ServiceLocatorImplBase implements IServiceLocator). So we can put the UnityServiceLocator or SpringServiceLocator in the CommonBootStrapper’s Locator variable. Now we need to two different bootstrappers for Unity and Spring.Net. The Unity implementation is shown below.
public class UnityBootStrapper : CommonBootStrapper
{
    protected override IServiceLocator CreateServiceLocator()
    {
        UnityContainer container = new UnityContainer();
        RegisterTypes(container);
        return new UnityServiceLocator(container);
    }
 
    private static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<ICustomer, GoldenCustomer>(typeof(ICustomer).FullName);
    }
}
As shown in code above, The UnityBootStrapper needs to override the CreateServiceLocator and in this method I have created an UnityContainer and packed it within UnityServiceLocator. For Spring.Net you can create an SpringServiceLocator with ObjectFactory packed in it.
4. Develop a BootStrapper Manager to provide a single point of access to Service Locator
Finally you need to develop a bootstrapper manager to hide the concrete implementation of CommonBootStrapper. The following code shows the BootStrapperManager
public class BootStrapperManager
{
    private static CommonBootStrapper _bootStrapper;
 
    public static void Initialize(CommonBootStrapper bootStrapper)
    {
        _bootStrapper = bootStrapper;
    }
    public static CommonBootStrapper BootStrapper
    {
        get { return _bootStrapper; }
    }
}
5. Access the IServiceLocator through BootStrapperManager
Now you need to register your BootStrapper to BootStrapperManager at some entry point to your application (like Main method). I have register as shown below:
BootStrapperManager.Initialize(new UnityBootStrapper());
Now from the application I only use CommonBootStrapper.Locator to get the IServiceLocator instance. So to get any instance from container I can write code like below:
ICustomer customer = CommonBootStrapper.Locator.GetInstance<ICustomer>(typeof(ICustomer).FullName);
customer.SendMessage("This is me.");

Conclusion

I have just gone through some basic ideas on how you can use Common Service Locator to decouple dependency to IoC Container from your production code. You can get more details on this visiting CodePlex link. For making my implementation I have included the Source Code from Common Service Locator in my Visual Studio Solution.

Sunday, June 21, 2009

Lambda Expression Tree

Lambda expression is parsed as tree under the hood. The lambda expression is parsed and stored as tree-shaped structure. Each node in the expression tree is represented as expression. System.Linq.Expressions.Expression class contains static factory methods that can be used to build and manipulate expression tree. The following figure shows how a simple expression is parsed and represented.

image

As the above figure shows, the expression is represented with two parameters: Body and Parameters. We had two parameters in the image above. Each parameter is of type Expression (ParameterExpression). FYI, there are several types of expressions(BinaryExpression, ConditionalExpression, ConstantExpression etc) that is derived from base Expression class. Also, Body is of type Binary Expression. So lets take an expression and dissect it.

Analyzing an Expression Tree

ay we have a function representing delegate  Func<int, bool>. The expression is:

Expression<Func<int, bool>> expressionTree =(i => i> 5);  

The expression has subparts that has shown in the image below

image

Here in the above statement we see the lambda expression takes an integer value and check if the value is greater than 5 or not and return a boolean value. The above expreesionTree variable's two property we have used in the code below. One is parameters collection and another one is Body. Parameters collection is of length one as we have only one parameter i

//This is i before the lambda expression

ParameterExpression param = expressionTree.Parameters[0] as ParameterExpression;

//this is the body of the expression, right side of lambda operator (=>). i.e., i>5

BinaryExpression  body=expressionTree.Body as BinaryExpression;

//This is the the i in the body. I.e., i on the left side of greater than

ParameterExpression left = body.Left as ParameterExpression;

//This is the constant in the body. That is 5

ConstantExpression right = body.Right as ConstantExpression;

Console.WriteLine("Docomposed Expression: {0} => {1} {2} {3}", param.Name, left.Name, body.NodeType, right.Value);

Building an Expression Tree

We can build the same expression tree that we have seen in above (for expression i=>i<5). All we need to do to generate different expressions (BinaryExpression, ConditionalExpression,ConstantExpression etc) and combine these properly into a single expression. Finally we need to compile and invoke the expression. A shown in the code snippet below, we can use Expression static methods to generate various types of expressions. we can generate a full function from that expression with Expression.Lambda method.

 

//bulild the prarameter expression

ParameterExpression param=Expression.Parameter(typeof(int),"i");

//build the constant expression

ConstantExpression constant = Expression.Constant(5, typeof(int));

//build the binary expression

BinaryExpression numLessThanAndEqual = Expression.LessThanOrEqual(param, constant);

//build the whole expression. that is body

Expression<Func<int, bool>> func = Expression.Lambda<Func<int, bool>>(numLessThanAndEqual, new ParameterExpression[] {param });

//complile the expression

Func<int,bool> compiledFounction = func.Compile();

//invoke the expression

compiledFounction.Invoke(10);

 

References

http://msdn.microsoft.com/en-us/library/bb397951.aspx

Friday, June 19, 2009

Lambda Expression: Basic and benefits

Generally, a Lambda Expression is anonymous function that use lambda expression (=>) which is read as "goes to". The format of the lambda expression is as follows:

parameters => body

Here if number of parameters is one the parenthesis is optional. If more than one parameters are used then parameters need to inside parenthesis. Also if the number of statements in body part is one then no second bracket is needed but if number of statement is more than one then statements need to inside second bracket. In the following code snippet I have declared two delegates. One represent integer binary operation signature and another is for unary operation signature.

 

The delegate with unary integer operation signature is as follows:

delegate int DelUnary(int i);

In the above statement the delegate name is DelUnary and it taken an integer value and return an integer value.

 

The delegate with binary operation signatue is as follows which takes two integer value and return an integer value:

delegate int delBinary(int t, int x);

 

Now lets talk about unary delegate. We need two methods for incrementing and decrementing values. So we can define these two functions and assign those two functions in a variable of type DelUnary as shown below:

            DelUnary increment = x => x++;

            DelUnary decrement = x => {x--};

In the above statement we have declared an variable (increment , decrement) of type DelUnary and then we have defined the body of the methods (increment, decrement). The body start after equal sign (=). The body part (x=x++;) or (x=>x--) has two parts. The left part of lambda operator (=>) is parameter (i.e., x) and right part of the lambda expression is the method body. The body may contains multiple statements but its recommended not to be more than 2/3 lines. In case of multiple statements you need to use curly braces({}) for enclosing statements.

Now we can call the method as

            int i=0;

            Console.WriteLine(increment(i));

            Console.WriteLine(decrement(i));

 

Similarly we can declare binary functions and call them as shown below:

            delBinary multiplication = ((x, y) => x * y);

            delBinary summation = ((x, y) => x * y);

            delBinary subtraction = ((x, y) => x * y);

 

            int m = 5;

            int n = 10;

            Console.WriteLine(multiplication(m, n));

            Console.WriteLine(subtraction(m, n));

            Console.WriteLine(summation(m, n));

 

Lambda expression allows us to write small code to do more. Lets say we have a collection of names and we need to find person whose name start with "mar". So in conventional C# we write something as shown below:

 

        string[] names = { "smith", "john", "mike", "mark", "seth", "maria", "manson" };

        IList<string> foundNames= new List<string>();

        foreach (string name in names)

        {

            if (name.StartsWith("mar"))

            {

                foundNames.Add(name);

            }

        }

 

But with lambda expression we can easily shorten the above code into small and more neat form as shown below:

string[] names = { "smith", "john", "mike", "mark", "seth", "maria", "manson" };

IList<string> foundNames = names.Where(s => s.StartsWith("mar")).ToList();

Isn't that goo huh? I like this coding style very much and I have used this style in my few new projects. Believe me I'm enjoying this coding style. When I started using lambda expression for the first time it was a kind of wired stuff to me. But as I'm exploring I'm finding this really interesting and I personally believe that it will increase programmer productivity as programmer need to write lees code.

Next time I'll explain Lambda Expression Tree which is also interesting.

Wednesday, June 17, 2009

CLR and .Net Framework: Some information to share

.Net Framework 4.0 in on the way and Vance Morrison, an CLR architect has talked about the how CLR has evolved from the the very beginning to till now. With .Net Framework 2.0 CLR version 2.0 was released. But with .Net Framework 3.x the CLR version was the same, i.e., CLR version 2.0. Now with .Net Framework 4.0 CLR version 4.0 is going to be launched. So Where is CLR version 3.0? Actually this does not exists and will never exists. To keep the CLR and .Net Framework version consistent CLR is named from 2.0 to 4.0.  I have recently come to know some new information about CLR and .Net Framework that are summarized below:

We can see source code of an assembly (if it's not encrypted) with reflector. Doesn't it break intellectual property?

Reflector unveil the source code and someone raise question about intellectual property but just unveiling source code doesn't mean the everything. A successful software system is more than just source code. Successful system is composed of dev team, test team, marketing policy, support team etc

Exception Modeling in CLR need to be optimized (As  per CLR Architect Vance Morrison)

The exception modeling in .net framework need to optimized. But the problem is that this will change the way programmer works. So changing the exception modeling, exiting exception handling may not work.

String Manipulation in CLR can be optimized (As per CLR Architect Vance Morrison)

By default string in .net takes two bytes of space as this is Unicode string. But in real world most of the systems are not multilingual system and needs only ANSI characters. So this is kind of waster of resources. Also more than 25--30% of the total resources in a system is string. So reducing the string size to half we can save around 10-15% of resources. So as per Vance Morrison, he has a vision to do something to make the string types configurable so that developers can specify which string they want to use.

Interface uses may create problem from version to version

We can't add default implementation of a method in an interface. For example in a class library version 1 an interface Interface1 has two methods. But in version 2 another one method is added. The problem is that with that new version of class library the older code will break. So Microsoft is working on .net framework to provide a way to say version 2 that "hey If this new method doesn't exist then create a default method"

Why multiple inheritance is not supported in c#?

The simple question is to make the implementation easier. If a class ClassA inherited from three different base class Base1, Base 2 and Base3 and each of them has a property (i wanna say state foo) then in composite object ClassA it might be difficult to find out which foo is to be incorporated in derived class. Some programming languages like C++ has virtual concept which may solve the problem but it make the inheritance model more complex and dotnet framework did not follow the path. These problem becomes even complex with diamond problem. State(class fields) are bad in this multiple inheritance as you need to decide which state to keep in case of multiple inheritance. But multiple contracts (methods) are fine as we can call the base contract(method) from derived one with prefixing base one (say Interface1.Contract1(), Interface2.Contract1() etc). So whether to allow multiple inheritance or not was a design problem for CLR designer and they choose not to allow multiple inheritance to avoid complexity with implementation. If multiple inheritance is supported then developer had to dealt with problems like diamond problem.

Monday, March 9, 2009

Tuple in C# 4.0

C# 4.0 include a new feature called Tuple. In mathematics tuple is a ordered list of specific number of values called the components of the tuple. For example a 3-tuple name may be used as: (First-Name, Middle-Name, Last-Name).

Let's take a look in the following example:

        public Tuple<int, int> GetDivAndRemainder(int i, int j)

        {

            Tuple.Create(i/j, i%j);

        }

        public void CallMethod()

        {

            var tuple = GetDivAndRemainder(10,3);

            Console.WriteLine("{0} and {1}", tuple.item1, tuple.item2);

        }

 

In the above example the method can return a tuple which has two integer values. So using tuple we can return multiple values. So this will help lazy programmers to write less code but do more. One great use of tuple might be returning multiple values from a method.


To get more info on Tuple visit the following links:

http://en.wikipedia.org/wiki/Tuple

http://peisker.net/dotnet/tuples.htm

http://spellcoder.com/blogs/dodyg/archive/2008/10/30/16319.aspx

Sunday, December 14, 2008

Jeffrey Richter’s Power Threading Library

Recently I have viewed the video on Jeffrey Richter's Power Threading Library and it's amazing. From this video I have got the idea that Asynchronous programming is possible with Synchronous approach. Jeffrey's Power Threading Library provides AsyncEnumrrator class which can be used for leveraging Asynchronous models with Synchronous model. Channel 9 video can be found http://channel9.msdn.com/posts/Charles/Jeffrey-Richter-and-his-AsyncEnumerator/. Finally the idea is really really great! We can find the related information from Jeffrey's blog from http://wintellect.com/PowerThreading.aspx

Friday, October 24, 2008

Provider Model (ASP.NET)

Provider model is just a way to allow user to contribute to API. For example you have a API with Class SecurityProvider:
public abstract class BaseSecurityProvider
{
    public bool Authenticate(string userName, string password);
}


Then you have defined an Sql2005SecurityProvider derived from BaseSecurityProvider as follows:
public class Sql2005SecurityProvider : BaseSecurityProvider
{
   public override bool Authenticate(string userName, string password)
    {
         //add logic here to authenticate against sql server 2005
     }
}


You have exposed your API with those Sql2005SecurityProvider so that user can authenticate against Sql server 2005. Now what if user wants to use Oracle or Active directory? May be one solution would be to implement another security provider such as OracleSecurityProvider. But it would be easier if we allow users to implement their own provider. To do so provider model is a best choice. To implement the provider model we need to refractor the BaseSecurityProvider abstract class. The modified code should look like as below:
    public abstract class BaseSecurityProvider
    {
        public bool Authenticate(string userName, string password);
        public static BaseSecurityProvider GetInstance()
        {
            string typeName = ConfigurationManager.AppSettings["TypeName"];
            string assemblyName = ConfigurationManger.AppSettings["AssemblyName"];
            BaseSecurityProvider securityProvider = System.Activator.CreateInstance(assemblyName, typeName);
        }
    }


Now users can implement a ActiveDirectory security provider class derived form BaseSecurityProvider and write necessary code in Authenticate method to authenticate against Active Directory:
public class ActiveDirectorySecurityProvider : BaseSecurityProvider
{
   public override bool Autheticate(stirng userName, string password)
   {
         //authenticate against AD.
    }
}

and then user can add the two entries in config file as
<AppSettings>
   <add key="AssemblyName" value................./>
   <add key="TypeName" value="ActiveDirectorySecurityProvider" />
</AppSettings>

Now to use your Active directory provider the code block will be
if (ActiveDirectorySecurityProvider .GetInstance().Authenticate(userName, password))
{
// authenticattion succeed
}

Now if a company say (Jaxara IT) supply the API with two class BaseSecurity provider and Sql2005SecurityProvider then another programmer of another company (say Orion Informatics Ltd.) can write a class inherited form BaseSecurityProvider to authenticate against another source.

For more information you can read Scott Mitchell's post here