1

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.

3 Answers 3

2

Here are the steps:

  1. Break the inheritance

    SPListItem targetItem = newWeb.Lists[uniqueListId].GetItemByUniqueId(uniqueItemId);
    if (!targetItem.HasUniqueRoleAssignments)
    {targetItem.BreakRoleInheritance(true);}
    
  2. Specify the target role definition (i.e., Full Controls,Contribute..)

    SPRoleDefinition oSPRoleDefinition = newWeb.RoleDefinitions.GetById(selectedPermissionId);
    
  3. Create a SPRoleAssingment using SPUser or SPGroup as the parameter

    SPRoleAssignment oSPRoleAssignment = new SPRoleAssignment(targetUser);
    
  4. Perform the binding

    oSPRoleAssignment.RoleDefinitionBindings.Add(oSPRoleDefinition);
    
  5. Add the role assignment to the target item.

    targetItem.RoleAssignments.Add(oSPRoleAssignment);
    

If you want to remove any default roleassingment to an item you can use this code:-

 SPRoleAssignmentCollection SPRoleAssColn = TargetItem.RoleAssignments;

 for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
 {
      SPRoleAssignment roleAssign = SPRoleAssColn[i];
      SPRoleAssColn.Remove(i);
 }

Hope this help.

1
  • Please see my edits.
    – V.B
    Oct 8, 2012 at 6:34
0

It should work, You are elevating Web Object Right ?

 SPSecurity.RunWithElevatedPrivileges(delegate
        {
            using (SPSite site = properties.Feature.Parent as SPSite)
            {
                SPWeb rootweb = site.RootWeb;
                SetPermissions(rootweb)
            }
        });

I have written a blog post for permission assignment http://sharepoint497.blogspot.com/2012/09/sharepoint-2010-security-using-object.html do check it out, it might help.

6
  • Well no I am not elevating right now.
    – V.B
    Oct 8, 2012 at 8:00
  • try elevating then Oct 8, 2012 at 8:09
  • Still no luck. It breaks inheritance just for one page.So elevating didn't work here.What I have done is calling my SetPermissions functions inside the Elevated scope.
    – V.B
    Oct 8, 2012 at 8:15
  • any idea why it just works for one page only?
    – V.B
    Oct 8, 2012 at 8:34
  • 1st use SPSecurity.RunWithElevatedPrivileges then initialize a new SPSite inside it and then initialize new SPWeb from this SPSite object, this will elevate SPWeb. Oct 8, 2012 at 10:15
0

Tthis is a feature to manage permissions list dynamically, by adding a rule based in column List or user profile service properties:

Permission Management, CodePlex

Your Answer

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

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