Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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.

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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.

share|improve this answer
    
thanks Agamand. –  V.B Jul 23 '12 at 8:35
    
Please see my edits. –  V.B Oct 8 '12 at 6:34

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

share|improve this answer

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.

share|improve this answer
    
Well no I am not elevating right now. –  V.B Oct 8 '12 at 8:00
    
try elevating then –  Salman Aziz Oct 8 '12 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 '12 at 8:15
    
any idea why it just works for one page only? –  V.B Oct 8 '12 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. –  Salman Aziz Oct 8 '12 at 10:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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