public static string getBrManagerFromAD(string ou)
{
using (HostingEnvironment.Impersonate())
{
string ouReplace = "";
if (ou.Contains("-"))
{
ouReplace = ou.Split('-')[0].Split(' ')[0];
}
string managerName = "";
try
{
List<Principal> allUsers = new List<Principal>();
// create your domain context and define the OU container to search in
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "ABC.LOCAL",
"OU=Users," + "OU=" + ouReplace + ",OU=Branch Offices,DC=ABC,DC=Local");
// define a "query-by-example" principal - here, we search for a UserPrincipal (user)
UserPrincipal qbeUser = new UserPrincipal(ctx);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach (var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
allUsers.Add(found);
}
foreach (Principal user in allUsers)
{
if (!string.IsNullOrEmpty(user.DistinguishedName))
{
DirectoryEntry dex = new DirectoryEntry("LDAP://" + user.DistinguishedName);
if (dex != null)
{
if (dex.Properties["title"].Count > 0)
{
if ((string)dex.Properties["title"].Value == "Manager")
{
managerName = (string)dex.Properties["displayName"].Value;
}
}
}
}
}
}
catch (Exception e)
{
Logging.SaveErrorLogData(e.Message, "getBrManagerFromAD");
}
return managerName;
}
}