Search code examples
c#active-directoryuserprincipalgroupprincipal

Server is unwilling to process the request when I try to save after remove member in Active Directory C#


I am analyzing and modifying a windows application about to sync data to Active Directory.

When I move users to another department in active directory,

I try to remove member in previous department.

And Member.Remove is fine, but when I try to save it, it throws exception like this

Server is unwilling to process the request

So, nothing was changed. Sadly, I'm a newbie of Active Directory, I don't know how to handle it.

The code is below. Please share your knowledge.

void MoveUser(string ppk, string pk)
{
   var aduser = adm.GetUser(pk);
   var adde=aduser.GetUnderlyingObject() as DirectoryEntry;
   var pde = adm.FindOU(ppk);
   if (aduser == null || pde == null)
   {
        return;
   }
   adde.MoveTo(pde);
   var pgroup = adm.GetGroup(ppk);
   if (!aduser.IsMemberOf(pgroup))
   {
        var allgroups = adm.GetAllDE(Words.Group);
        foreach (var sg in allgroups)
        {
            var samname = GetSamName(sg);
            var sgroup = adm.GetGroup(samname);
            if (aduser.IsMemberOf(sgroup))
            {
                sgroup.Members.Remove(aduser);
                //exception here
                //message: Server is unwilling to process the request
                sgroup.Save();
            }
        }
        pgroup.Members.Add(aduser);
        pgroup.Save();
    }
}

public UserPrincipal GetUser(string sUserName)
{
    PrincipalContext oPrincipalContext = GetPrincipalContext();
    UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
    return oUserPrincipal;
}

public DirectoryEntry FindOU(string ouName)
{
    DirectorySearcher ds = new DirectorySearcher(GetRootOu());
    ds.Filter = "(ou=" + ouName + ")";
    try
    {
        return ds.FindOne().GetDirectoryEntry();
    }
    catch (Exception)
    {
        return null;
    }
 }

public GroupPrincipal GetGroup(string sGroupName)
{
    PrincipalContext oPrincipalContext = GetPrincipalContext();

    GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, sGroupName);
    return oGroupPrincipal;
}

Solution

  • The comment from oldvets is correct. The distinguishedName is what is stored in the member attribute of the group. When you move the object, the DN changes.

    However, when you move the user, the aduser object is not getting updated with the new location. So when you now try to remove the user using aduser, it's trying to remove the old DN. That won't work.

    You're better off removing the membership first, then move the object to the new OU.