Thursday, June 17, 2010

BreakRoleInheritance Common mistake Tip for SharePoint Developers

Hi All,

This post is to share with SharePoint folks/Developers one of the common mistakes that i caught while debugging and reviewing one of my projects. They system is using Custom List to store Data. and we set the permissions in C#, Here is how to set the permissions on item level permissions in SharePoint 2007:

// Define Role Assignment object.
groupRoleAssignment = new SPRoleAssignment(SPContext.Current.Web.CurrentUser);

// Define the Permission Level you would like to give.
SPRoleDefinition readControlDef = SPContext.Current.Site.RootWeb.RoleDefinitions["Read"];

//Add Permissions to the Role
groupRoleAssignment.RoleDefinitionBindings.Add(readControlDef);

//Add the item to your custom list.
SPListItem myItem = web.Lists[RFIListName].Items.Add();

// Break the inheritance to add your custom - Note this step
myItem.BreakRoleInheritance(true);

// Add Role assignment to the created item.
myItem.RoleAssignments.Add(groupRoleAssignment);

myItem.Update();


To check the permissions on the item level in SharePoint 2007, here is the code you need to write:

SPListItem item = MyBLL.getListItem(Id);
// Check if the user has permissions to edit the item
if (!item.DoesUserHavePermissions(SPBasePermissions.EditListItems))
{// the user doesn't have permission to edit the item, do something...
}


The check above was returning True, even if the user doesn't have Edit/Contribute permissions on the item.

Why ?! If you check the above function on this line:
myItem.BreakRoleInheritance(true);

True: means copy the permissions first, then my code add more custom permissions. and this is not what i want, i don't want to inherit any permissions from the site.

False: Means don't copy and i will handle the permissions by my self. and this is what i want.

The Developer who wrote above lines didn't read the description of the function, he thought that he wants to break the permissions by setting it to true.

Lessons learned, and this is the point i want to share it with all.

Hope this helps.

Regards,
Mostafa arafa

No comments: