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("*");
Related
I want to get maxPwdAge value for specific Organization Unit or Group wise.Anybody help me how to do it.
I am able to get domain level maxPwdAge like below, but how can i get Group or OU level maxPwdAge.
Anybody please help me.
long maxPwdAge=0;
string domain="LDAP://10.10.1.100/OU=Dev,DC=test,DC=com";
string adsiUserName="test";
string adsiPassword="test";
DirectoryEntry entry = new DirectoryEntry(domain, adsiUserName, adsiPassword, AuthenticationTypes.Secure);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
string filter = "(maxPwdAge=*)"; //"maxPwdAge=*";
mySearcher.Filter = filter;
SearchResult results = mySearcher.FindOne();
if (results != null)
{
Int64 pwdAge = (Int64)results.Properties["maxPwdAge"][0];
maxPwdAge = pwdAge / -864000000000;
}
Your problem is most likely that you're filtering by password max age and not adding it to the properties.
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.
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.
I'm Trying to change a name of a group with c# and .NET. It's working well with the following code:
public void selectADSObject(string LDAP)
{
DirectoryEntry Entry = new DirectoryEntry(ADS_PATH);
Entry.Username = ADS_USER;
Entry.Password = ADS_PW;
DirectorySearcher Searcher = new DirectorySearcher(Entry);
Searcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
Searcher.Filter = LDAP;
AdObj = Searcher.FindOne();
AdObj.GetDirectoryEntry().Rename("cn=newName");
}
There is just the "windows-pre 2000" name that doesn't rename and I need it to rename too. On this page I figured out that the sAMAccountName is what I'm after. But when I add the following lines, it also doesn't change the pre-windows 2000 name:
AdObj.GetDirectoryEntry().Properties["sAMAccountName"].Value = "newName";
AdObj.GetDirectoryEntry().CommitChanges();
How can I change the sAMAccountName / pre-windows 2000 name?
Every time you invoke:
AdObj.GetDirectoryEntry()
It actually creates a new object! Every change is lost on the next line. Please use something like:
var dent = AdObj.GetDirectoryEntry()
dent.Properties["sAMAccountName"].Value = "newName";
dent.CommitChanges();
dent.rename("cn=newName");
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