Tuesday, April 21, 2020

Active directory (AD) get users as a drop down list by passing text, either Login ID, Email ID or by Starting display Name of User.


Active directory (AD) get users as a drop down list by passing text, either Login ID, Email ID or by Starting display Name of User.

Below is the c# code,
1. Adding by exact Email id
2. Adding exact Login user id
3. Name staring example 'Ash*'



internal static void GetUserDetails(string sKey)
        {
            try
            {

                sKey = "as";//ash.ash@....com//asharma1234

                List<Users> lstADUsers = new List<Users>();
                string DomainPath = "LDAP://DC=AMAT,DC=com";
                DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
                DirectorySearcher search = new DirectorySearcher(searchRoot);

                search.Filter = string.Format("(mail={0})", sKey);
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("sn");
                search.PropertiesToLoad.Add("usergroup");
                search.PropertiesToLoad.Add("displayname");//first name
                search.SizeLimit = 25;
                SearchResult result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("samaccountname") &&
                                 result.Properties.Contains("mail") &&
                            result.Properties.Contains("displayname"))
                        {
                            Users objSurveyUsers = new Users();
                            objSurveyUsers.Email = (String)result.Properties["mail"][0];
                            objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
                            objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
                            lstADUsers.Add(objSurveyUsers);
                        }
                    }
                }

                search.Filter = string.Format("(sAMAccountName={0})", sKey);
                search.SizeLimit = 25;
                result = null;
                resultCol = null;

                resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("samaccountname") &&
                                 result.Properties.Contains("mail") &&
                            result.Properties.Contains("displayname"))
                        {
                            Users objSurveyUsers = new Users();
                            objSurveyUsers.Email = (String)result.Properties["mail"][0];
                            objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
                            objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
                            lstADUsers.Add(objSurveyUsers);
                        }
                    }
                }

                search.Filter = string.Format("(&(objectClass=user)(givenname={0}*))", sKey);
                search.SizeLimit = 25;
                result = null;
                resultCol = null;

                resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("samaccountname") &&
                                 result.Properties.Contains("mail") &&
                            result.Properties.Contains("displayname"))
                        {
                            Users objSurveyUsers = new Users();
                            objSurveyUsers.Email = (String)result.Properties["mail"][0];
                            objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
                            objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
                            lstADUsers.Add(objSurveyUsers);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
}

    public class Users
    {
        public string Email { get; set; }
        public string UserName { get; set; }
        public string DisplayName { get; set; }
    }


/////---added no 20210129(get email by display name for a Group or Person/User)---/////

internal static List<Users> GetUserDetails(string sKey)

        {

            sKey = sKey.Contains("AMAT\\") ? sKey.Replace("AMAT\\", "") : sKey;

            List<Users> lstADUsers = new List<Users>();

            try

            {

 

 

 

                string DomainPath = "LDAP://DC=AMAT,DC=com";

                DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);

                DirectorySearcher search = new DirectorySearcher(searchRoot);

 

                search.Filter = string.Format("(mail={0})", sKey);

                search.PropertiesToLoad.Add("samaccountname");

                search.PropertiesToLoad.Add("mail");

                search.PropertiesToLoad.Add("sn");

                search.PropertiesToLoad.Add("usergroup");

                search.PropertiesToLoad.Add("displayname");//first name

                search.PropertiesToLoad.Add("objectCategory");

                search.PropertiesToLoad.Add("objectClass");

                search.SizeLimit = 25;

                SearchResult result;

                SearchResultCollection resultCol = search.FindAll();

 

                search.Filter = string.Format("(&(|(objectClass=user)(objectClass=group))(anr={0}))", sKey);

                //search.Filter = string.Format("(&(objectClass=user)(givenname={0}))", sKey);

                //search.Filter = string.Format("(&(objectClass = user)(| (displayName = *{0} *)(givenName = *{0} *)(sn = *{0} *)))", sKey);

                search.SizeLimit = 25;

                result = null;

                resultCol = null;

 

                resultCol = search.FindAll();

                if (resultCol != null)

                {

                    for (int counter = 0; counter < resultCol.Count; counter++)

                    {

                        string UserNameEmailString = string.Empty;

                        result = resultCol[counter];

                        if (result.Properties.Contains("samaccountname") &&

                                 result.Properties.Contains("mail") &&

                            result.Properties.Contains("displayname"))

                        {

                            Users objSurveyUsers = new Users();

                            objSurveyUsers.Email = (String)result.Properties["mail"][0];

                            objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];

                            objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];

                            if (Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("group"))

                                objSurveyUsers.UserType = "Group";

                            else if (Convert.ToString((String)result.Properties["objectCategory"][0]).ToLower().Contains("person"))

                                objSurveyUsers.UserType = "Person";

                            else

                                objSurveyUsers.UserType = "";

                            lstADUsers.Add(objSurveyUsers);

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                Users objSurveyUsers = new Users();

                objSurveyUsers.Email = "Error";

                objSurveyUsers.UserName = "Error";

                objSurveyUsers.DisplayName = ex.Message;

                lstADUsers.Add(objSurveyUsers);

            }

            return lstADUsers;

        }

 

--//////   sending mail by smtp  //////----

public static string SendMail(string to, string cc, string subject, string body)
        {
            try
            {
                string fromMail = Convert.ToString(ConfigurationManager.AppSettings["FromMail"]);
                string fromHost = Convert.ToString(ConfigurationManager.AppSettings["MailHost"]);
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);//ServicePointManager.SecurityProtocol | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12; ;
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(fromMail);
                string[] strTo = to.Split(',');
                foreach (string str in strTo)
                {
                    if (str.Trim() != "")
                    {
                        List<Users> oUsr = GetUserDetails(str);
                        foreach (Users u in oUsr)
                            if (u.DisplayName == str) mail.To.Add(u.Email);
                    }
                }
                if (!string.IsNullOrEmpty(cc))
                {
                    string[] strCc = cc.Split(',');
                    foreach (string str in strCc)
                        if (str.Trim() != "")
                        {
                            List<Users> oUsr = GetUserDetails(str);
                            foreach (Users u in oUsr)
                                if (u.DisplayName == str) mail.CC.Add(u.Email);
                        }
                }
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                mail.Body = body;
                SmtpClient smtp = new SmtpClient(fromHost);
                smtp.UseDefaultCredentials = true;
                //smtp.Credentials = new System.Net.NetworkCredential("IMA_SERVICE_ACCOUNT", "");
                smtp.EnableSsl = false;
                smtp.Send(mail);
                return "success";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }