Thursday, February 28, 2019

An error occurred while enumerating the groups. the group could not be found. : Get the Bad groups name.



Problem: An error occurred while enumerating the groups. the group could not be found.


In c#.net exception occurs. 
  1. Then way to find the bad group. Below is the code.
  2. First get all groups for a user in AD.
  3. Then loop through and get the object of Group Name. If not found then it will be null.
  4. Else it is a valid Group.
  5. "nullgrpname" variable contains all Bad Groups.


private void GetBadGroups(string groupName, string userName)
    {


        System.DirectoryServices.AccountManagement.PrincipalContext ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(
                                        System.DirectoryServices.AccountManagement.ContextType.Domain, "DOMAIN");
        // find a user
        System.DirectoryServices.AccountManagement.UserPrincipal uPrincipal = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(ctx, userName);
        string res = "";
        var sroles = uPrincipal.GetAuthorizationGroups();
        if (sroles != null && sroles.Count() > 0)
        {
            int i = 0;
            List<string> rs = new List<string>();
            while (i < sroles.Count()) //unknown error happens on some groups
            {
                try
                {
                    var role = sroles.ElementAt(i);
                    if (role != null && role.Name != null)
                        rs.Add(role.Name.ToUpper());
                }
                catch
                {
                    res += ("A bad group has been found on user:" + userName);
                }
                i++;
            }
            string[] roles = rs.ToArray();
            string ab1 = roles[0];
            ////   ---------------------------------
            string nullgrpname = "";
            foreach (string name in roles)
            {
                groupName = name;
                // set up domain context
                PrincipalContext ctx1 = new PrincipalContext(ContextType.Domain, "DOMAIN");

                // find a user
                UserPrincipal user = UserPrincipal.FindByIdentity(ctx1, userName);

                // find the group in question
                GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx1, groupName);
                if (group == null)
                {
                    nullgrpname += groupName + ";";
                }

                if (user != null && group != null)
                {
                    // check if user is member of that group
                    if (user.IsMemberOf(group))
                    {
                        // do something.....
                    }
                }
            }
        }
    }