Tuesday, November 3, 2009

Fetch user infromation from Active Directory

//Method to the list of userids in actvie directory
public bool GetUsers(string domain, string uname, string pwd, string distinguishName)
{
try
{
StringBuilder sb = new StringBuilder();
DirectoryEntry entry = new DirectoryEntry(distinguishName, uname, pwd, AuthenticationTypes.Secure);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
SearchResultCollection results;
mySearcher.Filter =“(objectClass=*)”;
mySearcher.SearchScope =SearchScope.Subtree;
results = mySearcher.FindAll();
foreach (SearchResult resEnt in results)
{
toolStripStatusLabel1.Text =“Connected to the LDAP/AD server.”;
ResultPropertyCollection propcoll = resEnt.Properties;
foreach (string key in propcoll.PropertyNames)
{
foreach (object values in propcoll[key])
{
switch (key)
{
case “userprincipalname”:
listBox1.Items.Add(values.ToString());break;
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
toolStripStatusLabel1.Text = ex.Message;
return false;
}
return true;
}

//method to get the distinguishedname from acive directory
public string GetObjectDistinguishedName(stringServerName)
{
try
{

if (!string.IsNullOrEmpty(ServerName))
{
toolStripStatusLabel1.Text =“Connecting to LDAP/AD server…”;
string distinguishedName = string.Empty;
DirectoryEntry entry = new DirectoryEntry(“LDAP://”+ ServerName);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter =“(objectClass=*)”;
SearchResult result = mySearcher.FindOne();
if (result != null)
{
//To get the distinguishedname

DirectoryEntry directoryObject = result.GetDirectoryEntry();
//set the distinguished name in a format
distinguishedName =“LDAP://” + ServerName + “/” + directoryObject.Properties["distinguishedName"].Value;entry.Close();
entry.Dispose();
mySearcher.Dispose();
return distinguishedName;
}

else
{

MessageBox.Show(“failed to connect”);
return null;
}
}



else
{
MessageBox.Show(“Please enter ServerName”);
return null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
toolStripStatusLabel1.Text = ex.Message;
return null;
}

No comments: