Just little about C#, .NET, SQL Server, SharePoint and SAP

Archive for October, 2009

Assigning Item Level Priviliges to SPListItem

Posted by zieglers on October 6, 2009


Sometimes you might wanna assign item level permissions to a list item instead of using Elevated Priviliges block throughout the whole code. This might happen in case you need to temporarily give a user higher priviliges than she has.

Typical example would be to provide a site reader exceptional functionality on a specific list item. In this case you break role inheritance and give the permissions you want. Here is a little snippet for that:



 …using SPSite…
    …using SPWeb…

// Get current user obj
SPUser user = SPContext.Current.Web.CurrentUser;
// Get current user token
SPUserToken token = user.UserToken;
// Get current user principal
SPPrincipal principal = (SPPrincipal)SPContext.Current.Web.CurrentUser;
// Get current user role assignment
SPRoleAssignment RoleAssignment = new SPRoleAssignment(principal);
// Get Your Custom Role definition
int SiteContributorId = -1;
SPRoleDefinition RoleDefSiteContributor = new SPRoleDefinition();

foreach (SPRoleDefinition roleDef in web.RoleDefinitions)
   // Find Your Custom Role Definition id
   if (roleDef.Name == “Your Custom Role Name”)
      SiteContributorId = roleDef.Id;

if (SiteContributorId != -1) {
   RoleDefSiteContributor = web.RoleDefinitions.GetById(SiteContributorId);
   // Add Your Custom Role to role assignments

if (!impersonatedListItem.HasUniqueRoleAssignments)
   // Break role inheritance

// Add Your Custom Role assignment to list item

 // Update changes

   …close using SPWeb…
…close using SPSite…



Posted in IT Stuff, SharePoint | Tagged: , , , , , | Leave a Comment »