I am working with SharePoint 2010 feature receivers. On feature activation I am creating multiple web part pages in library "Site Pages". I want to set individual permissions for each page, but I want it to be done as the page is created rather than going to SP and managing the permissions through UI. Could you please help me on setting up the permissions dynamically.
Here my sample code
private void SetPermissions(SPWeb web, string configurationFileName, string rootTag, string pageName)
{
try
{
SPList list = web.Lists[pagesLibrary];// "Site Pages"
SPQuery query = new SPQuery();
var pages = SPHelper.GetConfigurationElements(configurationFileName, rootTag);
foreach (var pagedef in pages)
{
//Get the SPListItemId by querying with item title.
int pageID = SPHelper.GetListItemIdByTitle(list, pageTitle);
// Check if page exists in the library.
if (pageID == 0)
continue;
// Get page item by page ID
query.RowLimit = 1U;
query.Query = string.Format("<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>{0}</Value></Eq></Where>", pageID);
SPListItemCollection items = list.GetItems(query);
if (items == null || items.Count < 1)
continue;
SPListItem page = items[0];
if (page == null)
continue;
// Check if page has unique permissions. If not then break the inheritance.
if (!page.HasUniqueRoleAssignments)
page.BreakRoleInheritance(false,true);
// Currently assigned roles.
SPRoleAssignmentCollection currentRoles = page.RoleAssignments;
// Remove current role assignments of the page.
for (int i = currentRoles.Count - 1; i >= 0; i--)
{
SPRoleAssignment roleAssign = currentRoles[i];
currentRoles.Remove(i);
}
// Read groups and roles from configuration file for each page/report.
var groups = pagedef.Elements(Groups).Elements();
foreach (var group in groups)
{
string groupName = group.GetAttribute(Name);
SPRoleType role = (SPRoleType)Enum.Parse(typeof(SPRoleType),group.GetAttribute(Role));
SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(role);
// Check if group exists in the site.
SPGroupCollection siteGroups = web.SiteGroups;
SPGroup oGroup = siteGroups.TryGet(groupName);
if (oGroup == null)
continue;
SPRoleAssignment roleAssign = new SPRoleAssignment(oGroup);
roleAssign.RoleDefinitionBindings.Add(roleDef);
page.RoleAssignments.Add(roleAssign);
}
}
}
catch (Exception ex)
{
throw;
}
}
This code use to work fine. But now It breaks the inheritance for just 1 item (page) in the list and upon checking the rest of the items (page.HasUniqueRoleAssignments) it always returns true which is not the case.
The above code is written at feature activation.
What I am doing wrong here.
Thanks.