Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the Active Directory server be contacted via PrincipalContext?

I am facing some problems in accessing Active Directory from my WinForm app. What I want is to create a user and query user from Active Directory.

Here is code snippet for find user:

public bool FindUser(string username)
{
    using (PrincipalContext context = new PrincipalContext(
        ContextType.Domain, 
        this.domainName, 
        this.DomainUserName, 
        this.DomainPassword))
    {                
        UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
        return (user != null) ? true : false;
    }
}

i am unable to create object of PrincipalContext based on given arguments. I am getting this exception:

Exception: The server could not be contacted.

and inner exception states that,

Inner Exception: The LDAP server is unavailable.

where as domain is running. I can ping to it and can also connect to this domain.

like image 357
Mohsan Avatar asked Nov 17 '09 10:11

Mohsan


2 Answers

You can try next code.

    public bool FindUser2(string userName)
    {
        try
        {
            DirectoryContext context = new DirectoryContext(
                DirectoryContextType.Domain,
                domainName,
                domainName + @"\" + domainUserName,
                domainPassword);
            DirectoryEntry domainEntry = Domain.GetDomain(context).GetDirectoryEntry();
            DirectorySearcher searcher = new DirectorySearcher(domainEntry,
                                                               "(|(objectCategory=user)(cn=" + domainUserName + "))");
            SearchResult searchResult = searcher.FindOne();
            return searchResult != null;
        }
        catch
        {
            return false;
        }
    }
like image 166
lerthe61 Avatar answered Oct 18 '22 21:10

lerthe61


You can use the following code:

objectPath = "LDAP://CN=SC-5515_2,OU=Forus,DC=**MyDomainName**,DC=no";

public static bool Exists(string objectPath)
{
    return DirectoryEntry.Exists(objectPath);
}

This is the code I have used for this. It works fine on testing if any objects exist in Active Directory.

like image 28
EKS Avatar answered Oct 18 '22 23:10

EKS