Run time exception while adding user to LDAP Server(Apache): System.Runtime.InteropServices.COMException: 'The directory service is unavailable.'

Viewed 28

Facing below runtime exception while adding user to LDAP Server(Apache) in C#:

System.Runtime.InteropServices.COMException: 'The directory service is unavailable.'

The below mentioned exception is the stackTrace value with

HResult -2147016689 at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)\r\n at System.DirectoryServices.DirectoryEntry.Bind()\r\n at System.DirectoryServices.DirectoryEntry.get_IsContainer()\r\n at System.DirectoryServices.DirectoryEntries.CheckIsContainer()\r\n at System.DirectoryServices.DirectoryEntries.Add(String name, String schemaClassName)\r\n at LdapExample.LdapConnector.AddUser(String path, User user).

The following function is used to add the user. Kindly let me know what is the problem with the implemented coding and solution to resolve the issue.

public class LdapConnector
{
    private readonly string domain;
    private readonly int port;
    private readonly LdapConnection ldapConnection;

    public LdapConnector(string domain, int port)
    {
        var ldi = new LdapDirectoryIdentifier(domain, port);
        this.ldapConnection = new LdapConnection(ldi);

        this.InitConnection();
        this.domain = domain;
        this.port = port;
        Console.WriteLine("Working");
    }

    public bool AddUser(string path, User user)
    {
        if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            return false;
        }

        DirectoryEntry rootDirectory = new DirectoryEntry($ "LDAP://{this.domain}:{this.port}/{path}");
        DirectoryEntries myEntry = rootDirectory.Children;
        rootDirectory.Children.Add(user.Username, "inetOrgPerson");
        //DirectoryEntry myDirectory= myEntry.Add("CN=Thomas", rootDirectory.SchemaClassName); // Tried this method too
        rootDirectory.CommitChanges();
        return false;
    }

    public User? GetUser(string username)
    {
        return null;
    }

    private void InitConnection()
    {
        ldapConnection.AuthType = AuthType.Basic;
        ldapConnection.SessionOptions.ProtocolVersion = 3;

        var nc = new NetworkCredential("uid=admin,ou=system", "secret"); //password
        ldapConnection.Bind(nc);
    }
}
0 Answers
Related