Groups are always created at the root level. An appweb
is a subsite, so you cannot create groups inside it. However, you can create groups in Hostweb
root site by creating a client context object of HostWeb
in case you use APP Event Receiver.
using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false))
You need to pass the second parameter as false
in TokenHelper.reateAppEventClientContext
. You can get host web url in Remote event receiver using query string.
hostUrl = new Uri(Request.QueryString["SPHostUrl"]);
Finally you need to give the app Full Control
permissions on the Host web. Follwing code can be used to create groups:
private void CreateGroup(GroupCollection collGroup, string groupName, Web oWebsite, ClientContext clientContext)
{
Group grp = collGroup.Where(g => g.Title == groupName).FirstOrDefault();
if (grp == null)
{
GroupCreationInformation groupCreationInfo = new GroupCreationInformation();
groupCreationInfo.Title = groupName;
groupCreationInfo.Description = "Description of " + groupName;
Group oGroup = oWebsite.SiteGroups.Add(groupCreationInfo);
RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(clientContext);
RoleDefinition oRoleDefinition = oWebsite.RoleDefinitions.GetByType(RoleType.Contributor);
collRoleDefinitionBinding.Add(oRoleDefinition);
oWebsite.RoleAssignments.Add(oGroup, collRoleDefinitionBinding);
clientContext.Load(oGroup, group => group.Title);
clientContext.Load(oRoleDefinition, role => role.Name);
clientContext.ExecuteQuery();
}
}
For more information please see my blog. Here I create groups in APP Event Receiver http://sharepointnadeem.blogspot.com/2014/02/sharepoint-2013-app-event-receivers.html