add

Thursday, June 11, 2009

How to get Data from Active Directory using C#

Today, I am going to discuss how to fetch data from active directory and how to store it into a clas..

We can access LDAP or AD by using two class: DirectoryEntry and DirectorySearcher

Step 1:

Add reference to System.DirectoryServices amd import it in the code by entering using System.DirectoryServices;

Step 2:

We need the AD Location, AD Userid and AD Password in order to read data from it.

We store these values in web.config:
<appSettings>
<add key="GaadLocation" value="LDAP://XXXXX:XXX"/>
<add key="GaadUserName" value="XXXXXX"/>
<add key="GaadPassword" value="XXXXXX"/>
</appSettings>


Step 3:

In order to store the data fetched from AD, we created a class and defined some properties.

public class ADContact
{
public string UniqueId {get; set; }
public string LastName { get; set; }
public string DepartmentNumber { get; set; }
public string EmployeeType { get; set; }
public string TelephoneNumber { get; set; }
public string FirstName { get; set; }
public string UserStatus { get; set; }
public string Mail { get; set; }
public string Mobile { get; set; }
public string Title {get; set; }
}


Step 4: Create a method that will return a datatable so that we can iterate through the result.

public List GetADContacts(string SirName, string GivenName, string UniqueId)
{}

Step 5:

Within the method, create a SearchResultCollection object , a datatable, and list of AD properties to access:

SearchResultCollection results = null;
List GaadData = new List();

string ADLocation, ADUserId, ADUserPassword = string.Empty;
#region List of AD Properties
string[] properties = new string[]
{
"modifyTimestamp",
"uid",
"sn",
"departmentNumber",
"facsimileTelephoneNumber",
"givenName",
"mail"
};
#endregion


Step 6:
Declare a try-catch block and within try- write the following code:

try {

string strfilter = string.Empty;


//Get AD Settings from web.config
ADLocation = ConfigurationManager.AppSettings["ADLocation"];
ADUserId = ConfigurationManager.AppSettings["ADUserName"];
ADUserPassword = ConfigurationManager.AppSettings["ADPassword"];


//Create an instance of DirectoryEntry by passing the setting valies)
DirectoryEntry root = new DirectoryEntry(ADLocation, ADUserId, ADUserPassword, AuthenticationTypes.FastBind);

//Create the filter string : we need to search the Ad for people matching the search criteria. Here we are passing three parameters: SirName, GivenName, Uid. If any field is blank, we are putting * there. that is to get all values

strfilter = String.Format(
"(&(&(sn={0})(givenname={1})(uid={2})))",
String.IsNullOrEmpty(SirName) ? "*" : SirName + "*",
String.IsNullOrEmpty(GivenName) ? "*" : GivenName + "*",
String.IsNullOrEmpty(UniqueId) ? "*" : UniqueId + "*");

if (strfilter != "")
{
DirectorySearcher searcher = new DirectorySearcher(root, strfilter, properties);
searcher.Asynchronous = true;
searcher.SearchScope = SearchScope.Subtree;
results = searcher.FindAll();
}
foreach (SearchResult result in results)
{
ADContact contact = new ADContact();

if (result.Properties["uid"].Count > 0)
contact.UniqueId= Convert.ToString(result.Properties["uid"][0]);

if (result.Properties["title"].Count > 0)
contact.Title = Convert.ToString(result.Properties["title"][0]);

if (result.Properties["sn"].Count > 0)
contact.LastName = Convert.ToString(result.Properties["sn"][0]);

if (result.Properties["givenName"].Count > 0)
contact.FirstName = Convert.ToString(result.Properties["givenName"][0]);

if (result.Properties["facsimileTelephoneNumber"].Count > 0)
contact.TelephoneNumber = Convert.ToString(result.Properties["facsimileTelephoneNumber"][0]);

if (result.Properties["mobile"].Count > 0)
contact.Mobile = Convert.ToString(result.Properties["mobile"][0]);

if (result.Properties["mail"].Count > 0)
contact.Mail = Convert.ToString(result.Properties["mail"][0]);

ADData.Add(contact);
}
return ADData;
}
catch (Exception ex)
{
throw ex;
}

1 comment:

Sunit Kundu said...

aageo porechi, kotha theke jhepechis--- Koushik