I would like to use the AccountManagement namespace introduced in .NET 3.5 to find a user and set their password. However, the ADLDS server is not part of our company domain so I'm using ContextType.Machine. When I search for the user it's never found (I suspect it's searching in the wrong container, but according to the documentation when using ContextType.Machine you can't specify a container).
using (var context = new PrincipalContext(ContextType.Machine, "test-server", null, "username", "password")) {
using (var u = UserPrincipal.FindByIdentity(context, "SuperAdmin")) {
//u is always null. :(
}
}
However, I know I can find the user using plain ol' DirectoryEntry:
using (var de = new DirectoryEntry("LDAP://test-server:389/CN=SuperAdmin,CN=SuperUsers,OU=test-server,DC=foo,DC=bar,DC=com", "username", "password", AuthenticationTypes.Secure)) {
//The user is found, but SetPassword fails with "The directory property cannot be found in the cache"
de.Invoke("SetPassword", new object[] { "foobar" });
}
One last thing to point out is that I can use ADSI Edit to change the password with these same credentials. Is it possible to use the newer directory objects to perform this search?
It's really an old question, but just recently I had to work on a similar project... I'll post the answer if anybody runs into the same issue.
The reason you cannot find the
userusingUserPrincipalclass is that as you mentioned you're searching usingContextType.Machine. But inDirectEntryclass you're just doing a simpleLDAP://query.Here's my solution.
I store my server information in
.configfile.I then created
ADLDSUtilityclass that returnsPrincipalContextobject.From there, I wrote a
methodthat accepts (username, currentPassword and newPassword) as paramaters.In this example, I'm searching user by
UserPrincipalName. But we are not limited to that. We can also search user byIdentityType.Guidetc.Now
searchUserhas two methods that involves password. I provided both of them.NOTE it's preferred to use SSL to set or change passwords.*