0

I am trying to create a user group in SharePoint using the following code:

// check if group exists
SPGroup newGroup = OfferWorkspaceUserGroup.GetGroup(web, name);

//create group with no users
if (newGroup == null) {
    //group does not exist -> create it
    web.SiteGroups.Add(name, owner, null, description);
    web.Update();
    newGroup = web.SiteGroups[name];
}

This code runs fine if the owner is the SharePoint Admin. If I set the owner to any normal user registered in the AD (that has access to the root site collection) the line

newGroup = web.SiteGroups[name];

throws an error saying that the group cannot be found.

However if I run the command web.SiteGroups I can see that the group exists.

I tried to give the owner full control which did not make a difference.

I am using C# and SharePoint 2013 Why am I seeing this behavior?

1
  • Can you please try your code in SPSecurity.RunWithElevatedPrievledge delegate
    – user13408
    Commented Jun 27, 2014 at 14:14

1 Answer 1

2

The problem is that the user doesn't have permissions to view the group membership. I'm attaching my own version of the AddGroup method. Please note the grp.OnlyAllowMembersViewMembership = false which sets the option for other users to check the group membership. Also you can check if a user has permissions to see the membership using the CanCurrentUserViewMembership property, this will avoid exceptions.

 private static void AddGroup(SPWeb web, SPRoleType roleType, string groupName)
    {
        var groups = web.SiteGroups;

        var userGroup = FindSiteGroup(web.Site, groupName);

        if (userGroup == null)
        {
            groups.Add(groupName, web.CurrentUser, null, string.Empty);
            web.AssociatedGroups.Add(web.SiteGroups[groupName]);
        }

        var grp = web.SiteGroups[groupName];
        grp.OnlyAllowMembersViewMembership = false;
        grp.Update();

        if (roleType != SPRoleType.None)
        {
            var asgn = new SPRoleAssignment(web.SiteGroups[groupName]);
            var roleDef = web.RoleDefinitions.GetByType(roleType);
            asgn.RoleDefinitionBindings.Add(roleDef);
            web.RoleAssignments.Add(asgn);
        }

        web.Update();
    }

-Hope it helps-

1
  • Thanks it helped as well as that I was ruining this code through a timer job which seemed to make additional trouble. The final solution was to put the code in to a featured which is the activated by the job. Took me quite a while to figure out that this code somehow can not be fun directly by the job. Commented Jul 2, 2014 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.