Error C# Invoke SetPassword AD

0

I'm trying to do a work for my final school project and I'm using C#, PHP, MySQL and Active Directory. The accounts will be created by the C# program into the Active Directory database, but I get this error while creating:

System.Reflection.TargetInvocationException: O destino de uma invocação accionou uma excepção. ---> System.Runtime.InteropServices.COMException: O servidor de RPC não está disponível. (Excepção de HRESULT: 0x800706BA)
   --- Fim do rastreio da pilha de excepção interna ---
   em System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args)
   em PAP.ldap_functions.createUser(String domain, String first, String last, String description, String password, String[] groups, String username, String email, Int32 mobile, String streetAddress, String city, String postalcode, Boolean enabled) em C:\Users\Karbust\source\repos\PAP\PAP\ldap_functions.cs:line 176

I'm using this code to do it:

        public int createUser(String domain, String first, String last, String description, String password, String[] groups, String username, String email, Int32 mobile, String streetAddress, String city, String postalcode, bool enabled)
        {
            try
            {
                // create new user object and write into AD             
                DirectoryEntry user = new DirectoryEntry(connectionstring_membros, adminlogin, adminpass);

                // User name (domain based)            
                DirectoryEntry objUser = user.Children.Add("CN=" + username, "user");

                // User name
                objUser.Properties["userPrincipalName"].Add(username + "@" + domain);

                // User name (older systems)           
                objUser.Properties["samaccountname"].Add(username);

                // Surname           
                objUser.Properties["sn"].Add(last);

                // Forename           
                objUser.Properties["givenname"].Add(first);

                // Display name           
                objUser.Properties["displayname"].Add(first + " " + last);

                // Description           
                objUser.Properties["description"].Add(description);

                // E-mail           
                objUser.Properties["mail"].Add(email);

                // Home dir (drive letter)           
                //objUser.Properties["homedirectory"].Add(homeDir);

                // Home dir (path)           
                //objUser.Properties["homedrive"].Add(homeDrive);

                objUser.CommitChanges();

                // set user's password             
                objUser.Invoke("SetPassword", password);
                //objUser.Properties["password"].Add(password);
                //objUser.SetPassword(password);
                //objUser.Invoke("SetPassword", new object[] { password });

                // Mobile Number
                objUser.Properties["mobile"].Add(mobile);

                // Telephone Number
                //objUser.Properties["telephoneNumber"].Add(telephoneNumber);

                // Street
                objUser.Properties["streetAddress"].Add(streetAddress);

                // City
                objUser.Properties["l"].Add(city);

                // State/Province
                //objUser.Properties["st"].Add(stateprovince);

                // Zip/Postal Code
                objUser.Properties["postalCode"].Add(postalcode);

                // enable account if requested (see http://support.microsoft.com/kb/305144 for other codes)              
                if (enabled)
                    objUser.Invoke("Put", new object[] { "userAccountControl", "512" });

                // add user to specified groups             
                foreach (String thisGroup in groups)
                {
                    DirectoryEntry newGroup = objUser.Parent.Children.Find("CN=" + thisGroup, "group");

                    if (newGroup != null)
                        newGroup.Invoke("Add", new object[] { objUser.Path.ToString() });
                }

                objUser.CommitChanges();

                // make home folder on server                      
                //Directory.CreateDirectory(homeDir);

                // set permissions on folder, we loop this because if the program           
                // tries to set the permissions straight away an exception will be           
                // thrown as the brand new user does not seem to be available, it takes           
                // a second or so for it to appear and it can then be used in ACLs           
                // and set as the owner             
                /*bool folderCreated = false;

                while (!folderCreated)
                {
                    try
                    {
                        // get current ACL                   
                        DirectoryInfo dInfo = new DirectoryInfo(homeDir);
                        DirectorySecurity dSecurity = dInfo.GetAccessControl();

                        // Add full control for the user and set owner to them                   
                        IdentityReference newUser = new NTAccount(domain + @"\" + username);
                        dSecurity.SetOwner(newUser);
                        FileSystemAccessRule permissions = new FileSystemAccessRule(newUser, FileSystemRights.FullControl, AccessControlType.Allow);
                        dSecurity.AddAccessRule(permissions);

                        // Set the new access settings.                   
                        dInfo.SetAccessControl(dSecurity);
                        folderCreated = true;
                    }
                    catch (System.Security.Principal.IdentityNotMappedException)
                    {
                        Console.Write(".");
                    }
                    catch (Exception ex)
                    {
                        // other exception caught so not problem with user delay as                  
                        // commented above                   
                        Console.WriteLine("Exception caught:" + ex.ToString());
                        return 0;
                    }
                }*/

                return 1;
            }
            catch(Exception ex)
            {
                MessageBox.Show("Exception caught: " + ex.ToString(), "Criar Cliente");

                fncs.ErroToTxt(ex);

                return 0;
            }
        }

The account is created but everything after

objUser.Invoke("SetPassword", password);

is not working, the program gives the exception is this line.

I'm using a code I found on the internet that is working 100% and adapted to my needs:

using System;
using System.Text;
using System.DirectoryServices;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.DirectoryServices.Protocols;
using System.DirectoryServices.AccountManagement;

namespace activeDirectoryLdapExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            // connect to LDAP             
            //DirectoryEntry myLdapConnection = createDirectoryEntry();

            // define vars for user             
            String domain = "vm.pap";
            String first = "First name";
            String last = "Last name";
            String description = ".NET Test";
            String password = "xpto001!";
            String[] groups = { "gr_membros" };
            //String username = first.ToLower() + last.Substring(0, 1).ToLower();
            String username = "charparodar";
            String email = "email@mail.com";
            String homeDrive = "H:";
            String homeDir = @"\\vm.pap\data3\USERS\" + username;

            // create user            
            try
            {
                if (createUser(domain, first, last, description, password, groups, username, email, homeDrive, homeDir, true) == 0)
                {
                    Console.WriteLine("Account created!");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("Problem creating account :(");
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught:\n\n" + e.ToString());
                Console.ReadLine();
            }
        }
        static int createUser(String domain, String first, String last, String description, String password, String[] groups, String username, String email, String homeDrive, String homeDir, bool enabled)
        {
            // create new user object and write into AD             
            //DirectoryEntry user = myLdapConnection.Children.Add("OU=" + first + ",OU= " + last, "user");
            //DirectoryEntry user = myLdapConnection.Children.Add("CN=" + first + " " + last, "user");
            DirectoryEntry user = new DirectoryEntry("LDAP://vmpap/OU=Membros,OU=Utilizadores,DC=vm,DC=pap", "Administrator", "xpto001!");

            // User name (domain based)            
            //user.Properties["userprincipalname"].Add(username + "@" + domain);
            //user.Invoke("Add", new object[] { username + "@" + domain });
            //user.Invoke("Add", new object[] { "ansilva15ig@vm.pap" });
            DirectoryEntry objUser = user.Children.Add("CN=ansilva15ig","user");

            // User name
            objUser.Properties["userPrincipalName"].Add(username + "@" + domain);

            // User name (older systems)           
            objUser.Properties["samaccountname"].Add(username);

            // Surname           
            objUser.Properties["sn"].Add(last);

            // Forename           
            objUser.Properties["givenname"].Add(first);

            // Display name           
            objUser.Properties["displayname"].Add(first + " " + last);

            // Description           
            objUser.Properties["description"].Add(description);

            // E-mail           
            objUser.Properties["mail"].Add(email);

            // Home dir (drive letter)           
            //objUser.Properties["homedirectory"].Add(homeDir);

            // Home dir (path)           
            //objUser.Properties["homedrive"].Add(homeDrive);

            objUser.CommitChanges();

            // set user's password             
            objUser.Invoke("SetPassword", password);

            // enable account if requested (see http://support.microsoft.com/kb/305144 for other codes)              
            if (enabled)
                objUser.Invoke("Put", new object[] { "userAccountControl", "512" });

            // add user to specified groups             
            foreach (String thisGroup in groups)
            {
                DirectoryEntry newGroup = objUser.Parent.Children.Find("CN=" + thisGroup, "group");

                if (newGroup != null)
                    newGroup.Invoke("Add", new object[] { objUser.Path.ToString() });
            }

            objUser.CommitChanges();

            // make home folder on server                      
            //Directory.CreateDirectory(homeDir);

            // set permissions on folder, we loop this because if the program           
            // tries to set the permissions straight away an exception will be           
            // thrown as the brand new user does not seem to be available, it takes           
            // a second or so for it to appear and it can then be used in ACLs           
            // and set as the owner             
            /*bool folderCreated = false;

            while (!folderCreated)
            {
                try
                {
                    // get current ACL                   
                    DirectoryInfo dInfo = new DirectoryInfo(homeDir);
                    DirectorySecurity dSecurity = dInfo.GetAccessControl();

                    // Add full control for the user and set owner to them                   
                    IdentityReference newUser = new NTAccount(domain + @"\" + username);
                    dSecurity.SetOwner(newUser);
                    FileSystemAccessRule permissions = new FileSystemAccessRule(newUser, FileSystemRights.FullControl, AccessControlType.Allow);
                    dSecurity.AddAccessRule(permissions);

                    // Set the new access settings.                   
                    dInfo.SetAccessControl(dSecurity);
                    folderCreated = true;
                }
                catch (System.Security.Principal.IdentityNotMappedException)
                {
                    Console.Write(".");
                }
                catch (Exception ex)
                {
                    // other exception caught so not problem with user delay as                  
                    // commented above                   
                    Console.WriteLine("Exception caught:" + ex.ToString());
                    return 1;
                }
            }*/
            return 0;
        }
        static DirectoryEntry createDirectoryEntry()
        {
            // create and return new LDAP connection with desired settings             
            DirectoryEntry ldapConnection = new DirectoryEntry("vm.pap");
            ldapConnection.Path = "LDAP://192.168.1.80/OU=Utilizadores,DC=vm,DC=pap";
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            return ldapConnection;
        }
    }
}

Thanks to everyone that tries to help

c#
active-directory
passwords
invoke
asked on Stack Overflow Nov 10, 2017 by Karbust

1 Answer

0

I tested on my end and affirm that your code works absolutely fine. So, there is nothing wrong with the code.

I was reading something and so as a solution, I would request you to temporarily disable the Firewall on PC where you are testing the software or application. Then test.

If it's a software application, test by running the software as Run as Administrator

answered on Stack Overflow Nov 14, 2017 by Vikram

User contributions licensed under CC BY-SA 3.0