October 2, 2009

Active Directory and C# VI

Time to continue this series of posts on the domain side. 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 once again refers to the sAMAccount, Groups and SID administration in AD.

public DirectoryEntry OpenEntryBySAMAccountName(string sAMAccountName)
{
//from config
string rootPath = SearchPath;
String filter = string.Format("(&(|(objectClass=user)(objectClass=group))(sAMAccountName={0}))", sAMAccountName);
string[] propsToLoad = new string[0];

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

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

if (sr == null)
return null;

return sr.GetDirectoryEntry();
}
}
}

public List GetAllGroupsSAMAccountNames()
{
List adGroups = GetAllGroups(new string[] { "sAMAccountName" });

try
{
List groups = new List();

foreach (AdGroup adGroup in adGroups)
groups.Add((string)adGroup.Entry.Properties["sAMAccountName"].Value);

return groups;
}
finally
{
Dispose(adGroups);
}
}

public List GetAllGroups(string[] propsToLoad)
{
//from config
string rootPath = GroupsSearchPath;
String filter = "(objectClass=group)";
List groups = new List();

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))
{
using (SearchResultCollection src = searcher.FindAll())
{
foreach (SearchResult sr in src)
{
groups.Add(new AdGroup(sr.GetDirectoryEntry()));
}
}
}
}

return groups;
}

private DirectoryEntry OpenRootDSE()
{
return OpenEntry("rootDSE");
}

public static Int64 UnboxAdsiInt64(object ADsLargeInteger)
{
IADsLargeInteger val = (IADsLargeInteger)ADsLargeInteger;
Int64 res = ((Int64)val.HighPart <<>
Turns out I need one more post for this to discuss password expiration and policy. Then this huge class file will be uploaded for you to use!

No comments:

Post a Comment