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.

No comments:

Post a Comment