September 29, 2009

Active Directory and C# IV

To continue this series of posts, I'd now like to talk about groups and my group helper class. It is actually quite simple and kind of looks just like the User helper. You can download all the files from here. I will upload this file from this post this week. You can see the first post related to this class file here. This post refers to the groups administration in AD.
  public AdGroup OpenGroup(string groupName)
{
if (groupName.IndexOf('=') != -1)
return OpenGroupByDN(groupName);
else
{
//GroupsSearchPath from config
if (string.IsNullOrEmpty(GroupsSearchPath))
throw new Exception("To search groups by SAMAccountName the PathToSearchForGroupsBySAMAcountName setting should be specified.");

return OpenGroupBySAMAccountName(groupName);
}
}

public AdGroup OpenGroupByDN(string groupDN)
{
DirectoryEntry entry = OpenExistingEntry(groupDN);

if (entry == null)
return null;

return new AdGroup(entry);
}

public AdGroup OpenGroupBySAMAccountName(string groupSAMAccountName)
{
//GroupsSearchPath from config
string rootPath = GroupsSearchPath;

String filter = string.Format("(&(objectClass=group)(sAMAccountName={0}))", groupSAMAccountName);
string[] propsToLoad = new string[0];

using (DirectoryEntry entry = OpenExistingEntry(rootPath))
{
if (entry == null)
throw new Exception(string.Format("Root to search groups by SAMAccountName failed to open. {0}", rootPath));

using (DirectorySearcher searcher = new DirectorySearcher(entry, filter, propsToLoad))
{
SearchResult sr = searcher.FindOne();

if (sr == null)
return null;

return new AdGroup(sr.GetDirectoryEntry());
}
}
}
I'll post one more time on this and also upload the file for you to download.

No comments:

Post a Comment