Sunday, December 25, 2022

Get User Id from AD

  public static List<UserInformation> GetADUsers(string username)

        {


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


            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++;

                                UserInformation userInfo = new UserInformation();

                                userInfo.UserName = de.Properties["displayName"].Value.ToString();

                                if (de.Properties["mail"].Value != null)

                                {

                                    userInfo.UserEmail = de.Properties["mail"].Value.ToString();

                                    userInfo.UserEmpID = de.Properties["employeeID"].Value.ToString();//NS

                                    if (de.Properties["manager"].Value != null)

                                    {

                                        string managerValue = de.Properties["manager"].Value.ToString();//NS


                                        DirectoryEntry deManager = new DirectoryEntry(Constants.ldap_AD_Path + managerValue);

                                        userInfo.UserManager = (string)deManager.Properties["displayName"].Value;

                                        userInfo.UserManagerID = (string)deManager.Properties["employeeID"].Value;                                        

                                        userInfo.UserCompanyRegion = (string)de.Properties["company"].Value;


                                    }

                                }


                                lstADUsers.Add(userInfo);

                                if (i == 10) break;


                            }

                        }

                    }

                }

            }

            return lstADUsers;

        }