2

I am trying to connect to the online test LDAP server specified here using System.DirectoryServices.AccountManagement like this:

try
{
    using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "ldap.forumsys.com:389", "dc=example,dc=com", "cn=read-only-admin,dc=example,dc=com", "password"))
    {
         using (var searcher = new PrincipalSearcher(new UserPrincipal(ctx )))
         {
              foreach (var result in searcher.FindAll().Take(usersCount))
              {
                 DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
              }
        }
    }
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}

But it throws the following exception:

Object reference not set to an instance of an object.

Could you please tell what is wrong with my code and how to be able to connect to that LDAP server?

PS: I am able to connect to that server using Apache Directory Studio

Stack Trace :

at System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties) at System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval() at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String container, ContextOptions options, String userName, String password) at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String container, String userName, String password) at ConsoleApp1.Program.GetGroups(String userName) in C:\Users\Simple Code\source\repos\ConsoleApp1\ConsoleApp1\Program.cs:line 48

Simple Code
  • 2,354
  • 2
  • 27
  • 56

2 Answers2

4

As said here, the problem could be that you try to connect to an Apache Directory Studio with the class PrincipalContext that not supports this OpenLDAP,

so one way to go is using the DirectoryEntry class

Ferus7
  • 707
  • 1
  • 10
  • 23
  • DirectoryEntry entry = new DirectoryEntry("ldap.forumsys.com:389", "cn=gauss,ou=mathematicians,dc=example,dc=com", "password"); DirectorySearcher searcher = new DirectorySearcher(entry) { PageSize = int.MaxValue, Filter = "(&(objectClass=user)(objectCategory=person))" }; searcher.PropertiesToLoad.Add("mail"); var result1 = searcher.FindOne(); – Simple Code Jan 04 '18 at 11:42
  • It throws "Unknown error (0x80005000)" on FindOne() – Simple Code Jan 04 '18 at 11:43
  • it doesn't work like that, [check](https://msdn.microsoft.com/en-us/library/39zxbb5w(v=vs.110).aspx) – Ferus7 Jan 04 '18 at 11:44
  • Thanks a lot. I would appreciate your help to help me out finding out the reason for that exception – Simple Code Jan 04 '18 at 12:25
  • @SimpleCode still getting that exception? – Ferus7 Jan 04 '18 at 12:29
  • I have posted my answer using DirectoryEntry and it's working now – Simple Code Jan 04 '18 at 12:30
  • @SimpleCode perfect! If my question helped you resolving =>`Connecting to LDAP server throws NullReferenceException`, feel free to mark as the correct one, glad to help you – Ferus7 Jan 04 '18 at 12:31
2

Using DirectoryEntry it works for me as following:

using (var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://ldap.forumsys.com:389/dc=example,dc=com", "", "", AuthenticationTypes.None)))
{
    searcher.Filter = "((objectClass=person))";
    searcher.PropertiesToLoad.Add("mail");//email
    searcher.PropertiesToLoad.Add("givenName");//first name
    searcher.PropertiesToLoad.Add("sn"); //last name
    searcher.PropertiesToLoad.Add("telephoneNumber");
    searcher.PropertiesToLoad.Add("description");
    searcher.PropertiesToLoad.Add("memberOf"); // groups

    var activeDirectoryStaffs = searcher.FindAll();
    if (activeDirectoryStaffs != null)
    {
        for (int i = 0; i < activeDirectoryStaffs.Count; i++)
        {
            SearchResult result = activeDirectoryStaffs[i];
            var Email = result.Properties.Contains("mail") ? (string)result.Properties["mail"][0]:null;
            var Mobile = result.Properties.Contains("telephoneNumber") ? (string)result.Properties["telephoneNumber"][0] : null;
            var FirstName = result.Properties.Contains("givenName") ? (string)result.Properties["givenName"][0] : null;
            var LastName = result.Properties.Contains("sn") ? (string)result.Properties["sn"][0] : null;
            var Description = result.Properties.Contains("description") ? (string)result.Properties["description"][0] : null;

        }
    }
}
Simple Code
  • 2,354
  • 2
  • 27
  • 56