Code - Alpha Solutions

In this Alpha Solutions Tech Tip, we share code for how to pull all the users in a user group by leveraging Entity Object properties.

2.12.20

BY NIKET ASHESH

While working on scripts in the new Sitecore Content Hub platform, I needed to get all the users who belonged to a particular user group. It took me a while to figure out how to do it, until I realized I needed to leverage the Entity Object properties. Hopefully, the following code will help you perform the same operation, quickly and easily.

From the StyleLabs documentation, we know how to get a UserGroup Entity:

var superUserGroup = await MClient.Users.GetUserGroupAsync("superusers");

if(superUserGroup == null){
   MClient.Logger.Debug($"no super user group found");
    return
}

 

Once we have the UserGroup, we can use the ID property to create a query for all the users related to this user group. Note the parent/child relationship and the composite filter.

  var query = new Query
            {
                Filter = new CompositeQueryFilter()
                {
                    Children = new QueryFilter[] {
                        new DefinitionQueryFilter{  Name="User"},
                    new RelationQueryFilter
                    {
                        Relation = "UserGroupToUser",
                        ParentId = superUserGroup.Id
                    }
                },
                    CombineMethod = CompositeFilterOperator.And
                }
            };
var users = await MClient.Querying.QueryIdsAsync(query);
if(users == null)
{
    MClient.Logger.Debug($"No super users found");
    return;
}
MClient.Logger.Debug($"Total number of super users is {users.TotalNumberOfResults}");

 

You can review the User Group Entity documentation here.