Tag Archive | Active Directory

Query Active directory for Username

I have been working on sharepoint-sap integration off late and have faced several challenges. One of those that i would like to share is extracting the windows account name from the firstname and lastname that you get it from SAP.

The windows account that you get from , can then be used to add users to the site. Enclosed is the snippet .

string strAdPath = “LDAP://dc=yourcompanyname,dc=com”;
string strUN= @”yourusername”;
string strPWD= “yourpassword”;
DirectoryEntry oLastEntry;
DirectoryEntry oFirstEntry;

public static DirectoryEntry GetDirectory()
{
DirectoryEntry oEntry = new DirectoryEntry(strAdPath ,strUN, strPWD, AuthenticationTypes.Secure);
return oEntry;
}

//Pass firstname and lastname to get the username

public string GetUserName(string firstName, string lastName)
{
DirectoryEntry oDirectoryEntry = GetDirectory();

DirectorySearcher oSearch = new DirectorySearcher(oDirectoryEntry);

//Search Criteria based on firstname
oSearch.Filter = “(&(objectClass=user)(givenName=” + firstName + “))”;

//Find all the records matching firstname
SearchResultCollection oResult = oSearch.FindAll();

//Loop through each records
foreach (SearchResult r in oResult)
{
oFirstEntry = r.GetDirectory();

//Check if the lastname of records retrieved matches with the lastname supplied
if ((string)oFirstEntry.Properties[“sn”].Value == lastName)
{
oLastEntry = r.GetDirectoryEntry();
}
}

//Get the username
if (oLastEntry != null)
{

userName = (string)userInfo.Properties[“samaccountname”].Value ?? string.Empty;
}

return userName;
}