Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Name Field on UserPrincipal

When I try to update the Name field (corresponds to the CN) on UserPrincipal (Principal, really), I get an error "The server is unwilling to process the request" on the call to UserPrincipal.Save().

I've checked to make sure there isn't another object in the same OU with the same Name (CN).

The PrincipalContext I'm operating at is the domain root (not exactly at the OU level where the user account exists).

What reason might there be for this error? Is it something that might be security policy related (even though I'm able to update all the other fields)?

using (var context = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["domain"], ConfigurationManager.AppSettings["rootDN"], ContextOptions.Negotiate, ConfigurationManager.AppSettings["username"], ConfigurationManager.AppSettings["password"])) {
    var user = UserPrincipal.FindByIdentity(context, IdentityType.Sid, "..."); // SID abbreviated

    user.Name = "Name, Test";

    user.Save();
}

The user I am using to create the PrincipalContext has the security rights to modify AD objects. If I update any other of the other fields (e.g. Surname, GivenName), everything works fine.

EDIT:

I've been able to accomplish what I need to do (using ADSI), but I have to run the following code under impersonation. The impersonation code is ugly, and the code below breaks away from the other way I'm updating AD data (using DirectoryServices.AccountManagement), so I'd like to get a better solution.

using (var companyOU = new DirectoryEntry("LDAP://" + company.UserAccountOU)) {
    companyOU.Invoke("MoveHere", "LDAP://" + user.DistinguishedName, "cn=Name\, Test");
}
like image 244
Chris Avatar asked Sep 13 '11 21:09

Chris


2 Answers

This is a cleaner way

using (var context = new PrincipalContext(ContextType.Domain))
{
    var group = GroupPrincipal.FindByIdentity(context, groupName);
    group.SamAccountName = newGroupName;
    group.DisplayName = newGroupName;
    group.Save();

    var dirEntry = (DirectoryEntry)group.GetUnderlyingObject();    
    dirEntry.Rename("CN=" + newGroupName);
    dirEntry.CommitChanges();
}
like image 157
Anonymous Avatar answered Sep 19 '22 07:09

Anonymous


The only way I've found to do this is in the EDIT section in my question. Basically, you cannot use the UserPrincipal class. There is something special about the CN attribute, and you need to drop down a level and use DirectoryEntry, an LDAP string, and invoke the "MoveHere" ADSI command to rename the user account.

like image 25
Chris Avatar answered Sep 22 '22 07:09

Chris