I'm working with custom templates in Sharepoint online and I want to
assign groups to lists automatically when a subsite is created. What I did:
- Created a template in Visual Studio
- Added an Event Receiver to the last Feature
- Filled the featureactivated method with the script below
What should happen is that when a subsite is created, the featureactivated method will fire and the specified groups will get assigned with their rights to a list.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
using (SPSite site = properties.Feature.Parent as SPSite)
{
SPWeb web = (SPWeb)properties.Feature.Parent;
try
{
SPList internalNotes = web.Lists.TryGetList("Internal Notes");
SPList externalNotes = web.Lists.TryGetList("Notes");
SPGroup headOfArtists = web.SiteGroups.GetByName("Head of Production");
SPGroup stageDesigners = web.SiteGroups.GetByName("Logistics Manager");
web.BreakRoleInheritance(true);
Tools.GroupHandler.addGroupToSPWeb(web, SPRoleType.Editor, headOfArtists);
Tools.GroupHandler.addGroupToSPWeb(web, SPRoleType.Reader, stageDesigners);
internalNotes.BreakRoleInheritance(true);
externalNotes.BreakRoleInheritance(true);
Tools.GroupHandler.addGroupToSPList(web, SPRoleType.Reader, headOfArtists, externalNotes);
Tools.GroupHandler.removeGroupFromList(web, stageDesigners, externalNotes);
}
catch (Exception e)
{
logger.LogError("Failed to add rights", e);
}
}
The GroupHandler class is a static class which looks like this:
public static class GroupHandler
{
public static void addGroupToSPWeb(SPWeb web, SPRoleType roleType, SPGroup group)
{
try
{
SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group);
SPRoleDefinition roleDefinitionRead = web.RoleDefinitions.GetByType(roleType);
roleAssignment.RoleDefinitionBindings.Add(roleDefinitionRead);
web.RoleAssignments.Add(roleAssignment);
}
catch (Exception e)
{
logger.LogError("Failed to add rights", e);
}
}
public static void addGroupToSPList(SPWeb web, SPRoleType roleType, SPGroup group, SPList list)
{
try
{
SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group);
SPRoleDefinition roleDefinitionRead = web.RoleDefinitions.GetByType(roleType);
roleAssignment.RoleDefinitionBindings.Add(roleDefinitionRead);
//list.RoleAssignments.Remove(group);
list.RoleAssignments.Add(roleAssignment);
}
catch (Exception e)
{
logger.LogError("Failed to add rights", e);
}
}
public static void removeGroupFromList(SPWeb web, SPGroup group, SPList list)
{
try
{
list.RoleAssignments.Remove(group);
}
catch (Exception e)
{
logger.LogError("Failed to add rights", e);
}
}
}
The Problem
When I create a subsite with the template that contains this event receiver, the event receiver just throws away the groups I want to assign to a specific list (in the example above "Head of Production and "Logistics Manager". I can't debug anything because it's Sharepoint online and everything worked fine in my Sandbox Solutions test environment.