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");
Related
The following code returns all the computerprincipals that have logon date prior to 3 months ago but does not get those with null for a lastlogontimestamp
PrincipalContext context = new PrincipalContext(ContextType.Domain);
PrincipalSearchResult<ComputerPrincipal> computers = ComputerPrincipal.FindByLogonTime(context, DateTime.Now.AddMonths(-3), MatchType.LessThanOrEquals);
How can I elegantly also add to "computers" those that have null valued "lastlogontimestamp" values?
I did away with the ComputerPrincipal.FindByLogonTime, since it can't find null LogonTime and went with the old classic, the DirectorySearcher
DirectorySearcher Computersearcher = new DirectorySearcher
{
SearchRoot = new DirectoryEntry(baseOU),
Filter = "(&(whenCreated<=" + WhenCreated + ")(!(userAccountControl=2))(|(lastLogonTimestamp<=" + DateInt + ")(lastLogonTimestamp=0))(objectClass=computer))",
SearchScope = SearchScope.Subtree,
PageSize = 1000,
Sort = new SortOption("Name", SortDirection.Ascending)
};
SearchResultCollection ComputerResults = Computersearcher.FindAll();
}
This has the unfortunate side effect that the observable collection that I used to create, no longer displays the Name in my WPF Listbox (despite setting DisplayNamePath).
A whole new issue, but the current one is "solved"
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("*");
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.
How i get the list of active directory user attributes(not of particular user i.e.all attributes) e.g.cn,mail etc. using c#?
If you're on .NET 3.5 and up, you need to check out the classes in System.DirectoryServices.ActiveDirectory for this. You need to look at classes like ActiveDirectorySchema and ActiveDirectorySchemaClass.
You can get hold of the current AD schema by using:
ActiveDirectorySchema currSchema = ActiveDirectorySchema.GetCurrentSchema();
When you have the current schema, you can inspect the various class definitions, e.g.:
ActiveDirectorySchemaClass userSchema = currSchema.FindClass("person");
Once you have that object, you can inspect and enumerate its properties, things like:
MandatoryProperties
OptionalProperties
and so on to get an insight into the AD schema.
DirectoryEntry dir = new DirectoryEntry();
dir.Path = "LDAP://YourActiveDirServername ";
DirectorySearcher sea = new DirectorySearcher(dir);
sea.Filter = "(sAMAccountName=Uname)";
SearchResult seares = sea.FindOne();
StringBuilder str = new StringBuilder();
System.DirectoryServices.ResultPropertyCollection prop = seares.Properties;
ICollection coll = prop.PropertyNames;
IEnumerator enu = coll.GetEnumerator();
while (enu.MoveNext())
{
str.Append(enu.Current + " = " + seares.Properties[enu.Current.ToString()][0] + "\n");
}
Also, take a look at: http://www.codeproject.com/KB/system/everythingInAD.aspx
You could use WMI:
ObjectGetOptions objectGetOptions = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
ManagementClass managementClass = new ManagementClass("root\\directory\\LDAP", "ads_user", objectGetOptions);
foreach (PropertyData dataObject in managementClass.Properties)
{
Console.WriteLine(dataObject.Name);
}
While ADExplorer does not list all the available attributes, I have found it a great tool for seeing what goes where.
You can download it from http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx
UserPropertyList = new List<string>();
ActiveDirectorySchema currSchema = ActiveDirectorySchema.GetCurrentSchema();
ICollection Collection = currSchema.FindAllProperties();
IEnumerator Enumerator = Collection.GetEnumerator();
while (Enumerator.MoveNext())
{
UserPropertyList.Add(Enumerator.Current.ToString());
}
The above code will add all search attributes of Active Directory to the UserPropertyList...
Expanding on marc_s's answer here. Here is a complete code example that prints the common name and the actual attribute name.
ActiveDirectorySchema schema = ActiveDirectorySchema.GetCurrentSchema();
ActiveDirectorySchemaClass person = schema.FindClass("user");
foreach( ActiveDirectorySchemaProperty property in person.GetAllProperties() )
{
Console.WriteLine("{0} = {1}", property.CommonName, property.Name);
}
Example output.
Common-Name = cn
Instance-Type = instanceType
NT-Security-Descriptor = nTSecurityDescriptor
Object-Category = objectCategory
Object-Class = objectClass
Object-Sid = objectSid
SAM-Account-Name = sAMAccountName
Account-Expires = accountExpires
...
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