Tuesday, July 27, 2021

CHECK USER IN ACTIVE DIRRECTORY GROUP C#

 CHECK USER IN ACTIVE DIRRECTORY GROUP C#

public static bool EnsureUserInADGroup(string groupName, string userName)

        {

            bool retValue = false;

            try

            {

                userName = userName.Replace(Constants.AMAT + "\\", "");

 

                PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Constants.AMAT);

                UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName);

                GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, groupName);

                if (user != null && grp != null)

                    retValue = grp.GetMembers(true).Contains(user);

                grp.Dispose();

            }

            catch (Exception e1)

            { retValue = false; }

            return retValue;

        }


        public static UserPrincipal GetUserDetailsPrincipal(string userName)
        {
            using (var context = new PrincipalContext(ContextType.Domain))
            {
                var usr = UserPrincipal.FindByIdentity(context, userName);
                return usr;
            }
        }

in helper.cs

where you want emp id

UserPrincipal userPrincipal = Helper.GetUserDetailsPrincipal(User.Identity.Name);

userPrincipal.EmployeeId