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 ListGetUserGroups(DirectoryEntry user)
{
Listgroups = new List ();
//we are building an '|' clause
Listsids = 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