Search code examples
.netactive-directoryldapdirectoryservicesadsi

Trying to create a new Active Directory user, Invoke("SetPassword",pwd) throws "The RPC server is unavailable"


I'm trying to create a new user on my development active directory server using .NET System.DirectoryServices namespace.

I try using the following code:

DirectoryEntry dirEntry = new DirectoryEntry(path, "TESTDOM\\Administrator", "2109password", AuthenticationTypes.Secure | AuthenticationTypes.ServerBind);

object o = dirEntry.NativeObject;
DirectoryEntry newUser = dirEntry.Children.Add("CN=NewUser4", "user");
newUser.Properties["samAccountName"].Value = "NewUser4";
newUser.Properties["Description"].Add("User Description");

newUser.Invoke("SetPassword",  new object[] {"2109password"} );
newUser.CommitChanges();

I also tried committing using

newUser.CommitChanges();

before I call the Invoke to set the password. I always get a TargetInvocationException wrapping:

InnerException {"The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"} System.Exception {System.Runtime.InteropServices.COMException}

The exception is always only thrown when I call

newUser.Invoke("SetPassword",  new object[] {"2109password"} );

If I call newUser.CommitChanges() before I try to call Invoke with SetPassword, the new user is created on the domain. I can then go manually to the AD machine and set the same password with no problems (so it's not a problem with the password string being against the rules). I've notice many post online about this but found no solution.

I think it might have something to do with the fact that the machine running the code is not a member in the domain. Although the user TESTDOM\Administrator is a member of the: administrators, domain admins, schema admin and enterprise admins groups on the TESTDOM domain.

Notice that I can't use System.DirectoryServices.AccountManagement namespace as I'm working with .NET 2 Any ideas on what can I do to solve this? I am desperate


Solution

  • OK, I got it working:

     dirEntry = new DirectoryEntry(ldapPath, domainAdminUser, domainAdminPassword);
        dirEntry.Invoke("SetPassword", new object[] { newPassword });
        dirEntry.Properties["LockOutTime"].Value = 0; //unlock account
    

    ldapPath should include the full DN of the user we're trying to change , so it should look something like:

    string ldapPath = "LDAP://ad.domain.com:389/CN=username,OU=Users,DC=ad,DC=domain,DC=com"