Updating Name Field on UserPrincipal

Chris Dwyer picture Chris Dwyer · Sep 13, 2011 · Viewed 8.9k times · Source

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");
}

Answer

Anonymous Boar picture Anonymous Boar · Jan 9, 2014

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();
}