Ir para o conteúdo
  • Revista PROGRAMAR: Já está disponível a edição #58 da revista programar. Faz já o download aqui!

charparodar

Erro C# Invoke SetPassword Active Directory

Mensagens Recomendadas

charparodar    0
charparodar

Boas a todos

Estou a tentar fazer o trabalho para a minha PAP, usando C#, PHP, MySQL e o Active Directory. As contas vão ser criadas pelo programa C# na base de dados do Active Directory, mas sempre que tento criar uma conta recebo este erro:

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

Estou a usar este código:

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

A conta é criada, mas na execução desta linha:

objUser.Invoke("SetPassword", password);

recebo o erro indicado em cima e o para por aqui, já não executa o resto dos comandos...

Estou a usar um código que encontrei na net, no qual a conta é criada e não recebo nenhum erro:

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[] { "charparodar@vm.pap" });
            DirectoryEntry objUser = user.Children.Add("CN=charparodar","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;
        }
    }
}

Alguém sabe como resolver este problema?

O servidor do Active Directory é o mesmo, a ser usado no Windows Server 2012 R2.

Obrigado

Editado por charparodar

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Crie uma conta ou ligue-se para comentar

Só membros podem comentar

Criar nova conta

Registe para ter uma conta na nossa comunidade. É fácil!

Registar nova conta

Entra

Já tem conta? Inicie sessão aqui.

Entrar Agora


×

Aviso Sobre Cookies

Ao usar este site você aceita os nossos Termos de Uso e Política de Privacidade