Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Wednesday, January 12, 2011

Facade Pattern in C#

O'Reilly's modern classic Head First Design Patterns describes the Facade pattern as a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

This pattern is nothing revolutionary and something that all programmers have done at some point, but it is good to have a common name to go by. Today I will demonstrate how to create and remove groups in Active Directory by building a facade.

First, start Visual Studio and create a new project using the class library template. Once created, add a reference to ActiveDs in the project. Next, add a new class named ActiveDirectoryFacade.cs and add Using System.DirectoryServices to that class. Now, add the following function to create a group...


public static bool CreateGroup(string groupName, out string result)
{
bool returnValue = false;
result = "";

try
{
DirectoryEntry groups = new DirectoryEntry();
groups.Path = "LDAP://ldap/OU=EmailGroups,DC=yourdomain,DC=com";
groups.AuthenticationType = AuthenticationTypes.Secure;

DirectoryEntry group = groups.Children.Add(String.Format("CN={0}", groupName), "group");
group.Properties["groupType"].Value = ActiveDs.ADS_GROUP_TYPE_ENUM.ADS_GROUP_TYPE_GLOBAL_GROUP;
group.Properties["mail"].Value = String.Format("{0}@yourdomain.com", groupName);
group.CommitChanges();

result = String.Format("Successfully created distribution list {0}", groupName);
returnValue = true;
}
catch (Exception ex)
{
result = ex.Message;
returnValue = false;
}

return returnValue;
}


...and add the following function to remove a group...


public static bool RemoveGroup(string groupName, out string result)
{
bool returnValue = false;
result = "";

try
{
DirectoryEntry groups = new DirectoryEntry();
groups.Path = "LDAP://ldap/OU=EmailGroups,DC=yourdomain,DC=com";
groups.AuthenticationType = AuthenticationTypes.Secure;

DirectoryEntry group = groups.Children.Find(String.Format("CN={0}", groupName));
if (group != null)
{
groups.Children.Remove(group);
group.CommitChanges();
}

result = String.Format("Successfully removed distribution list {0}", groupName);
returnValue = true;
}
catch (Exception ex)
{
result = ex.Message;
returnValue = false;
}

return returnValue;
}


We have just created a facade to add and remove Active Directory Groups with two functions. We can now use these functions in our applications.

Friday, October 1, 2010

Abstract Factory Pattern In C#.Net

Sometimes when building and application you need to plan for changes that you cannot possibly plan for. For example, if you are building an application to import data from different sources and you will receive that data in completely different formats one, approach might be to create a different application for each import. That's a valid approach, but one that requires a good deal of code duplication. Let us examine the Abstract Factory pattern and see how it might help us here.

Both the old classic Design Patterns (Gamma, Helm, Johnson and Vlissides) and the new classic Head First Design Patterns from O'Reilly (Freeman and Freeman) define the Abstract Factory pattern as a way to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes. " What does that actually mean? In the example business problem from above, we could create a class for each import type that implements an interface, therefore decoupling the import parsing from the persistence of the data. In other words, we don't have to write a new application for each import type, just a new class.

The first thing I will do is create a new project and then add an Enum named ParsableType and an Interface named IImportParsable.

public class ParsableTypes
{
public enum ParsableType
{
Excel = 1,
FixedFormat = 2
}
}

public interface IImportParsable
{
bool Parse();
}

Next, I will create 2 new classes that implement our interface...

public class ExcelParser : IImportParsable
{
public bool Parse()
{
//do some excel parsing here
return true;
}
}

public class FixedFormatParser : IImportParsable
{
public bool Parse()
{
//do some text file parsing here
return true;
}
}

Next, we need a factory to determine which parser to use...
public class ImportParsableFactory
{
public static IImportParsable GetImportParser(ParsableTypes.ParsableType parsableType)
{
IImportParsable importParsable = null;

switch (parsableType)
{
case ParsableTypes.ParsableType.Excel :
importParsable = new ExcelParser();
break;

case ParsableTypes.ParsableType.FixedFormat :
importParsable = new FixedFormatParser();
break;
}

return importParsable;
}
}

Finally, we just need a controller to get the parse type and then call the parse method...
public void Import(int parseID)
{
IImportParsable importParser = ImportParsableFactory.GetImportParser((ParsableTypes.ParsableType)parseID);
importParser.Parse();
}
}

As new parse needs arise, we just add an enum entry, create a new class that implements IImportParsable and add another case to our switch and we are done. We have a nice decoupled approach that we can use by itself or combine with the Facade or Decorator patterns to add even more pattern goodness.

Monday, September 13, 2010

Singleton Design Pattern

Sometimes you need to guarantee that only one instance of a class is created. One example might be a database object where you only want one connection. This class should be available globally, but should only have one instance. The Singleton creational pattern conforms to this requirement.

The O'Reilly book Head First Design Patterns By Eric and Elisabeth Freeman define the Singleton Pattern as a class that has only one instance and provides a global point of access to it.

The classic book Design Patterns by Gamma, Helm, Johnson and Vlissides (Gang of Four) add the following points.

Participants
  • Singleton
  1. Defines an Instance operation that lets clients access it unique instance. Instance is a class operation.
  2. May be responsible for creating its own unique instance.

For my example, I'll create a singleton class in c# using the .Net Framework 4.0 that has a connection object in it. First, start a new console app project. Next, add a new class and name it Singleton.cs with following code...

namespace SingletonExample
{
public sealed class Singleton
{
private static readonly SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=Chinook;Integrated Security=SSPI;");

static Singleton()
{
}

Singleton()
{
}

public static SqlConnection Connection
{
get
{
if (connection.State == ConnectionState.Closed) connection.Open();
return connection;
}
}
}
}

Now, in your program.cs file add the following code to Main...

static void Main(string[] args)
{
SqlConnection connection1 = singleton.connection;
SqlConnection connection2 = singleton.connection;
SqlConnection connection3 = singleton.connection;
SqlConnection connection4 = singleton.connection;
SqlConnection connection5 = singleton.connection;

Console.ReadLine();
}

As you step through the code run sp_who2 on the Chinook database and you will see only one connection added.

By the way, the Chinook database is on Codeplex and is designed as alternative to Northwind. It's small, will run on SQL Server, Oracle and MySQL and installs with a single script.