Get "Home Directory" attribute from active directory - c#

I'm trying to get Home Directory attribute value from active directory..
I used the following code:
public static void GetExchangeServerByWwidLdap(string wwid)
{
var exchange = string.Empty;
using (var ds = new DirectorySearcher())
{
ds.SearchRoot = new DirectoryEntry("GC:something");
ds.SearchScope = SearchScope.Subtree;
//construct search filter
string filter = "(&(objectclass=user)(objectcategory=person)";
filter += "(employeeid=" + wwid + "))";
ds.Filter = filter;
string[] requiredProperties = new string[] { "homeDirectory", "homemta" };
foreach (String property in requiredProperties)
ds.PropertiesToLoad.Add(property);
SearchResult result = ds.FindOne();
}
}
When I check result object data, I'm seeing only 2 values: "homemta" and "adspath".
Where is the "homeDirectory" value?
I entered AD website and searched the same values for same users - through the website I can see the all the data I searched for so I assuming that I have code issue somewhere.
What am I doing wrong?

You're trying to retrieve homeDirectory from global catalog.
It’s not there.
You can e.g. bind to the user by ADsPath property (i.e. “LDAP://…” string), then query the homeDirectory attribute of that user.
Or, if you only have a single domain, you can search within that domain instead of searching the GC. In this case you'll be able to retrieve all the properties you want.

Related

read Parent-GUID attribute from ActiveDirectory using C#

I want to read Parent-GUID attribute from ActiveDirectory.
I have tried below code to read all attributes of AD object from ActiveDirectory.
Code
var dirEntry = new DirectoryEntry(directoryEntryPath);
var directorySearcher = new DirectorySearcher(dirEntry, filter)
{
CacheResults = false,
Tombstone = true,
};
var searchResult = directorySearcher.FindAll(); // get mutiple AD Objects
foreach (SearchResult search in searchResult)
{
foreach (DictionaryEntry prop in search.Properties) // here I get all attributes values But not able to find parent-GUID attribute
{
}
}
Using above code I am able to get all properties of AD Object but I am not able to get value of Parent-GUID attribute.
According to https://learn.microsoft.com/en-us/windows/desktop/adschema/a-parentguid this is a constructed attribute. This means it won't be included in search results. The docs also imply it's there to support DirSync which tells me that it might not be available outside of a DirSync search.
Do you mean something like that?:
string path = "CN=someone,OU=yourOrganizationalUnit,DC=example,DC=com";
DirectoryEntry root = new DirectoryEntry(path);
root.Parent.Guid.ToString(); // this will display you the GUID from the parent of your path
Hope this is what you meant!
Cheers,
ov4rlrd
var searchResult = directorySearcher.FindAll();
foreach(SearchResult search in searchResult)
{
DirectoryEntry de = search.GetDirectoryEntry();
Guid ParentGUID = new Guid((byte[])de.Parent.Properties["objectGUID"][0]);
...
}

Get direct reports ID in LDAP

I am using the LDAP for retrieving the hierarchy in my organisation. Under the property directreports I am getting all the names of the employees reporting under me. But I want to get their unique Identification (may be some employee id). How can I do that?
You can try this-
Add System.DirectoryServices.AccountManagement references in your project and import the namespaces.
var listOfDirectReportsNames = // Get the list of all the directreports user names and store in list- List<string>();
var pc = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, Environment.UserDomainName);
foreach (string name in listOfDirectReportsNames)
{
var up = new System.DirectoryServices.AccountManagement.UserPrincipal(pc);
up.Name = name; //to test this, pass the exact LDAP Name/DisplayName/GivenName of any user
System.DirectoryServices.AccountManagement.PrincipalSearcher searcher = new System.DirectoryServices.AccountManagement.PrincipalSearcher(up);
var res = searcher.FindOne();
string empID = ((System.DirectoryServices.AccountManagement.UserPrincipal)res).EmployeeId;//here you will get employee ID
up.Dispose();
}

Search LastName and FirstName in AD

I want to retrieve the first name and last name of the user that is logged in his/her machine using AD. I use the following code:
string server = ConfigurationManager.AppSettings["ActiveDirectory.Server"];
DirectoryEntry entry = new DirectoryEntry(#"LDAP://" + server);
DirectorySearcher searcher = new DirectorySearcher(entry);
User user = GetUser(entry);
searcher.Filter = "sAMAccountName=" + user.UserAD;
searcher.PropertiesToLoad.Add("memberof");
SearchResult result = searcher.FindOne();
private static User GetUser(DirectoryEntry userEntry)
{
Usuario user = new User();
string[] username = HttpContext.Current.Request.ServerVariables["AUTH_USER"].Split('\\');
//THIS IS WHAT I NEED BUT IT DOES RETURN null.
//User.Name= (string)userEntry.Properties["givenName"].Value;
//User.LastName= (string)userEntry.Properties["sn"].Value;
user.Domain = username[0];
user.UserAD = username[1];
return user;
}
Now, I know searcher.PropertiesToLoad have a [memberof] and [adspath], the last one gives me the first and last name separated with a comma, something like CN="gates, billy" but I dont want to use substrings and index, is there any property like [firstName], [lastName] in the list properties?
I did search that DirectoryEntry have a property called givenName and sn but this returns null
The PropertiesToLoad set is exactly what you need to modify. Active Directory will return only the properties which are defined in this set, that's why you don't see givenName and sn. Just add these properties as well:
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("sn");
Alternatively, just add the property * to load all of them:
searcher.PropertiesToLoad.Add("*");

c# DirectoryEntry.Properties vs DirectoryEntry.InvokeGet?

I have a strange problem when I tried to retrieve the "AccountExpirationDate" from the active directory.
I use the following code to retrieve the user:
DirectoryEntry dirEntry = new DirectoryEntry(Path);
DirectorySearcher search = new DirectorySearcher(dirEntry);
// specify the search filter
search.Filter = "(&(objectClass=user)(mail=" + email + "))";
// perform the search
SearchResult result = search.FindOne();
DirectoryEntry user = result.GetDirectoryEntry();
And then I retrieve the "AccountExpirationDate":
object o1 = user.Properties["accountExpires"].Value; //return a COM object and I cannot retrieve anything from it
object o2 = user.Properties["AccountExpirationDate"].Value; //return null
object o3 = user.InvokeGet("AccountExpirationDate"); //return the DateTime
So I would like to what happened here?
Why I cannot use DirectoryEntry.Properties to retrieve the AccountExpirationDate?
What is the different between DirectoryEntry.Properties vs DirectoryEntry.InvokeGet?
Thanks a lot.
You can tell a directorySearcher which properties to load as follows:
// specify the search filter
search.Filter = "(&(objectClass=user)(mail=" + email + "))";
search.PropertiesToLoad.Add("AccountExpirationDate");
search.PropertiesToLoad.Add("displayname");
after performing search you need to go through the properties of the SearchResult to get values
i.e.
object o1 = result.Properties["AccountExpirationDate"][0];
DirectoryEntry.Properties - Gets the Active Directory Domain Services properties for this DirectoryEntry object.
DirectoryEntry.InvokeGet - Gets a property from the native Active Directory Domain Services object.
//Microsoft doesn't recommend the use of InvokeGet method.

Active Directory search - filter by Manager

I'm trying to get a list of users from the Active Directory, who have a specified manager.
I used the following LDAP filter without success:
(manager=CN=Misterboss_n*)
However, it returns no result. Users have the following value in the manager attribute:
"CN=Misterboss_n,OU=xyz user,DC=xyz,DC=local"
What am I doing wrong? If I replace the above filter with something like this:
(givenName=John*)
it works okay (returns all users whose given name is John).
Wider context:
public List<ADUserDetail> GetAllEmployeesUnderMisterboss()
{
List<ADUserDetail> userlist = new List<ADUserDetail>();
string filter = "";
_directoryEntry = null;
DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
directorySearch.Asynchronous = true;
directorySearch.CacheResults = true;
filter = "(manager=CN=Misterboss_n*)";
directorySearch.Filter = filter;
SearchResultCollection userCollection = directorySearch.FindAll();
foreach (SearchResult users in userCollection)
{
DirectoryEntry userEntry = new DirectoryEntry(users.Path, LDAPUser, LDAPPassword);
ADUserDetail userInfo = ADUserDetail.GetUser(userEntry);
userlist.Add(userInfo);
}
return userlist;
}
Thanks for the help!
I don't think there is a start-of-field search available for DN-typed properties. You will have to use the full DN of the manager. If you don't know the full DN, find the manager's LDAP object first and use its distinguishedName property.
Be sure to escape the DN value properly before building your filter - not every character that is valid in a DN is also valid in an LDAP filter expression:
* as \2a
( as \28
) as \29
\ as \5c
NUL as \00
/ as \2f
For code samples, see this related thread where I answered a very similar question: Getting all direct Reports from Active Directory

Categories