I have MVC2 application which has windows authentication. for the user mapping purpose I have loaded all the AD users in to the drop down.I have new requirement to that take all AD users in different domains to above mentioned drop down.In order i Need to get user's details such as first name, last name etc.Can some one tell is there any possible way to implement this using c#? Below is my code that i am using to take all AD users in single forest.
List<UserMgtModelsMetadata> userList = new List<UserMgtModelsMetadata>();
string username = ConfigurationManager.AppSettings["ADUsername"].ToString();
string password = ConfigurationManager.AppSettings["ADPassword"].ToString();
string path = ConfigurationManager.AppSettings["Path"].ToString();
string domain = ConfigurationManager.AppSettings["Domain"].ToString();
DirectoryEntry myLdapConnection = new DirectoryEntry(path, username, password);
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.PropertiesToLoad.Add("displayname");
search.PropertiesToLoad.Add("samaccountname"); //Username
search.PropertiesToLoad.Add("givenname"); //Firstname
search.PropertiesToLoad.Add("sn"); //Lastname
search.PropertiesToLoad.Add("userprincipalname");
search.PropertiesToLoad.Add("memberof");
SearchResultCollection result = search.FindAll();
if (result != null)
{
for (int i = 0; i < result.Count; i++)
{
ResultPropertyCollection fields = result[i].Properties;
if ((fields["displayname"].Count > 0) && (fields["samaccountname"].Count > 0) && (fields["givenname"].Count > 0) && (fields["sn"].Count > 0) && (fields["userprincipalname"].Count > 0))
{
string mail = fields["userprincipalname"][0].ToString();
int index = mail.IndexOf("@") > 0 ? mail.IndexOf("@") : 0;
string fullName = (fields["givenname"][0].ToString() +" "+ fields["sn"][0].ToString());
if (fullName.Length > 20)
{
fullName = fullName.Substring(0, 20);
}
if (!group.Equals(" "))
{
bool isMember = false;
foreach (var item in fields["memberof"])
{
isMember = item.ToString().Contains("CN=" + group);
if (isMember == true)
{
break;
}
}
if (isMember == true)
{
userList.Add(new UserMgtModelsMetadata
{
displayName = fullName,
username = fields["samaccountname"][0].ToString(),
firstName = fields["givenname"][0].ToString(),
lastname = fields["sn"][0].ToString(),
email = mail.Substring(0, index).ToLower() + domain
});
}
}
else
{
userList.Add(new UserMgtModelsMetadata
{
displayName = fullName,
username = fields["samaccountname"][0].ToString(),
firstName = fields["givenname"][0].ToString(),
lastname = fields["sn"][0].ToString(),
email = mail.Substring(0, index).ToLower() + domain
});
}
}
}`