Saturday, April 25, 2020

Autocomplete text box , content directly from AD, Name, Email etc


Autocomplete text box , content directly from AD, Name, Email etc
---------------------------------------------------------------------


[WebMethod]
        public static List<UserProperty> GetADUsers(string username)
        {
            List<UserProperty> lstADUsers = new List<UserProperty>();

            if (!string.IsNullOrEmpty(username))
            {
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
                {
                    UserPrincipal user = new UserPrincipal(context);
                    user.DisplayName = username + "*";
                    using (PrincipalSearcher srch = new PrincipalSearcher(user))
                    {
                        int i = 0;
                        foreach (var result in srch.FindAll())
                        {
                            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                            if (!String.IsNullOrEmpty((String)de.Properties["displayName"].Value))
                            {
                                i++;
                                UserProperty usp = new UserProperty();
                                usp.UserName = de.Properties["displayName"].Value.ToString();
                                if (de.Properties["mail"].Value != null)
                                    usp.Email = de.Properties["mail"].Value.ToString();

                                //if (de.Properties["EmployeeId"].Value != null)
                                //{
                                //    usp.EmpId = de.Properties["EmployeeId"].Value.ToString();
                                //}
                                //else
                                //    usp.EmpId = string.Empty;

                                lstADUsers.Add(usp);
                                if (i == 10) break;

                            }
                        }
                    }
                }
            }
            return lstADUsers;
        }