PrincipalContext for query in Active Directory

czWolfHunter picture czWolfHunter · Jan 18, 2013 · Viewed 18.2k times · Source

I want to make a few simple reports from Active Directory. Following discussions, etc. I found that if I use .NET FW 3.5 and up, it is appropriate to use PrincipalContext. I would like to understand principles and what I can do with this new feature (unlike DirectoryEntry).

Code skeleton

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, 
    "YOURDOMAIN", "OU=SomeOU,DC=YourCompany,DC=com");

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// which has a password that will expire in 3 days or less
UserPrincipal userTemplate = new UserPrincipal(ctx);
userTemplate.AdvancedSearchFilter.AccountExpirationDate(DateTime.Today.AddDays(3), MatchType.LessThanOrEquals);

// instantiate searcher
PrincipalSearcher searcher = new PrincipalSearcher(userTemplate);

// enumerate matching users
foreach (Principal foundPrincipal in searcher.FindAll())
{
    UserPrincipal foundUser = (foundPrincipal as UserPrincipal);

    if (foundUser != null)
    {
        // do something with users found - e.g. send e-mail
    }
}

It is possible by code up add this properties for login to LDAP?:

  • what LDAP is used (version 2 or 3)
  • how set port on which LDAP is running
  • how to work if I need SSL connection? (different port, must be special requirements)

Furthermore, can I do with AdvancedSearchFilter this conditions?
(I found only AccountExpirationDate and AccountLockoutDate)

  • users password will expire in the near future
  • users password has expired
  • check if the user's password can expire
  • users account expires (account, no password)
  • expired users account (account, no password)
  • user account not expired

Answer

czWolfHunter picture czWolfHunter · Feb 7, 2013

sorry for the late reply. The solution I found these two links, which describes all the information. Just as it only needs to combine with the code above.

retrieve the value of "Minimum Password Length" in domain password policy

House of Derek - Password expiration email utility