October 1, 2009

Active Directory and C# V

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 refers to the sAMAccount, Groups and SID administration in AD.
 
public AdUser OpenUserBySAMAccountName(string userSAMAccountName, params string[] propsToLoad)
{
//usersearchpath from config
string rootPath = UsersSearchPath;
String filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", userSAMAccountName);

using (DirectoryEntry entry = OpenExistingEntry(rootPath))
{
if (entry == null)
throw new Exception(string.Format("Root to search user 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 AdUser(sr.GetDirectoryEntry());
}
}
}

public string GetSidPath(DirectoryEntry entry)
{
byte[] sidBytes = (byte[])entry.Properties["objectSid"][0];
SecurityIdentifier sid = new SecurityIdentifier(sidBytes, 0);
return string.Format("LDAP://", sid.ToString());
}

public List GetUserGroups(DirectoryEntry user)
{
List groups = new List();

//we are building an '|' clause
List sids = new List();
user.RefreshCache(new string[] { "tokenGroups" });
foreach (byte[] sid in user.Properties["tokenGroups"])
{
//append each member into the filter
sids.Add(string.Format("(objectSid={0})", BuildFilterOctetString(sid)));
}

if (sids.Count == 0)
return groups;

//end our initial filter
string filter = "(|" + string.Join("", sids.ToArray()) + ")";
//GroupsSearchPath from config
DirectoryEntry searchRoot = OpenEntry(GroupsSearchPath);
using (searchRoot)
{

//we now have our filter, we can just search for the groups
DirectorySearcher ds = new DirectorySearcher(
searchRoot,
filter
);

using (SearchResultCollection src = ds.FindAll())
{
foreach (SearchResult sr in src)
{
groups.Add((string)sr.Properties["samAccountName"][0]);
}
}
}

return groups;
}

private string BuildFilterOctetString(byte[] bytes)
{
StringBuilder sb = new StringBuilder();

for (int i = 0; i < bytes.Length; i++)
{
sb.AppendFormat("\\{0}", bytes[i].ToString("X2"));
}

return sb.ToString();
}


I'll upload this file tomorrow. This will make it a lot easier to follow.

No comments:

Post a Comment