Thursday, September 30, 2010

ActiveDirectory and Csharp - Finding the domain user via email

Sometimes, how many examples, and none seem to work.

I wanted to lookup and verify a user exists via email, in a process that reads email via pop, and then creates records in Silverlight/Lightswitch application.

So how do it?

I've included the code below. Not that a normal user is fine for the username and password, and you must supply the domain controller. I used the IP of mine.

1:  public DirectoryEntry find_by_email(string email)
  
2:    {
  
3:      DirectoryEntry dirEntry = new DirectoryEntry("LDAP://10.0.7.100","ausername","apassword",AuthenticationTypes.Secure);
  
4:      DirectorySearcher Dsearch = new DirectorySearcher(dirEntry);
  
5:      Dsearch.Filter = "(&(objectCategory=person)(sAMAccountName=*)(mail="+email+"))";
  
6:      SearchResult sResult = Dsearch.FindOne();
  
7:      if (sResult == null)
  
8:      {
  
9:        return null;
  
10:      }
  
11:      EventLog.WriteEntry("DoneEmailLookup");
  
12:      DirectoryEntry user = sResult.GetDirectoryEntry();
  
13:      return (user);
  
14:    }
  

No comments: