Get User Info from Active Directory using LDAP




using log4net;

using System.DirectoryServices;

public class ADUserInfo

{

public string ShortName { get; set; }

public string DisplayName { get; set; }

public string Email { get; set; }

}

The following method returns ADUser information:


[Serializable]

[DataObject(true)]

public class ADUtilities

{

private static readonly ILog log = LogManager.GetLogger(typeof(ADUtilities));


///

/// Returns UserInfo Object,

/// Which contains User Display Name,Email Address

///

/// User ShortName

public static List< ADUserInfo> GetCurrentUserInfo(string _userName)

{

if (String.IsNullOrEmpty(_userName))

{

log.Error("UserName is null or Empty for GetCurrentUserInfo[_userName]: " + _userName);

return null;

}

try

{

string ldapqry = ConfigurationManager.AppSettings["ADConnctionstr"].ToString(); //@"LDAP://DC01.eng.stclocal";

string qryFilterFormat = String.Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))", _userName);

SearchResult result = null;

using (DirectoryEntry root = new DirectoryEntry(ldapqry))

{

using (DirectorySearcher searcher = new DirectorySearcher(root))

{

List< ADUserInfo> userInfo = new List<InfiniaUserInfo>();

ADUserInfo objuser = new InfiniaUserInfo();

searcher.Filter = qryFilterFormat;

SearchResultCollection results = searcher.FindAll();

result = (results.Count != 0) ? results[0] : null;

objuser.ShortName = (string) result.Properties["sAMAccountName"][0];

objuser.DisplayName = (string)result.Properties["displayname"][0];

if(!String.IsNullOrEmpty((string)result.Properties["mail"][0]))

objuser.Email = (string)result.Properties["mail"][0];

//else

//objuser.Email = (string)result.Properties["sAMAccountName"][0];

userInfo.Add(objuser);

return userInfo;

}

}

}

catch (Exception ex)

{

log.Error("Error to getting Email Address for GetCurrentUserEmail [username] : " + _userName + " Error Message: " + ex.Message.ToString());

return null;

}

}

}


Comments

Popular posts from this blog

Windows Azure Package Build Error: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Resource ID : 1. The request limit for the database is 180 and has been reached.

How to get Client's Location using IPAddress