Monday, March 25, 2013

Setting SharePoint list item level permissions programmatically

Inside collections SharePoint supports setting permissions on four levels: Web, List, Folder, Item. By default child elements inherit permission from parent (e.g. child web from parent web, item from folder etc.), but you can break this inheritance at any level. But remember, that web with very granular permissions is hard to maintain. Consider you want to give permissions to new user, then you have to duplicate it in every item with unique permissions. So think well before you break permission inheritance, and try to do it at higher level (list or folder) rather than lower However, sometimes the only way is to set unique permission per list item.
So, when you decided how you will manage permissions on your site or list, the next step is to choose proper place to write your code. The most popular variants, which are suitable for most cases, are event handlers and workflows. Remember that workflow is executed in system account context, so you can manage permissions without any problems, but event handler is executed in current user context, so you need to elevate user context first.
The code for adding permissions to SharePoint list item or folder can be following:

        public static void AddPermission(SPListItem item, SPPrincipal principal, SPRoleType role)

        {
            SPWeb web = item.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate() { 
                using(SPSite elevatedSite = new SPSite(web.Site.ID))
                {
                    elevatedSite.AllowUnsafeUpdates = true;
                    using (SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID))
                    {
                        elevatedWeb.AllowUnsafeUpdates = true;
                        SPList list = elevatedWeb.Lists[item.ParentList.ID];
                        SPListItem elevatedItem = (item.FileSystemObjectType == SPFileSystemObjectType.Folder) ?
                            list.Folders.GetItemById(item.ID) : list.Items.GetItemById(item.ID);
                        SPRoleDefinition roleDefinition = !string.IsNullOrEmpty(roleName) ?
                            elevatedWeb.RoleDefinitions[roleName] : elevatedWeb.RoleDefinitions.GetByType(role);
                        SPRoleAssignment roleAssigment = new SPRoleAssignment(principal);
                        roleAssigment.RoleDefinitionBindings.Add(roleDefinition);
                        if (!elevatedItem.HasUniqueRoleAssignments)
                        {
                            elevatedItem.BreakRoleInheritance(true);
                        }
                        elevatedItem.RoleAssignments.Add(roleAssigment);
                        elevatedSite.AllowUnsafeUpdates = false; 
                        elevatedWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

Here item is item or folder, and principal is user or group. Pay attention to setting AllowUnsafeUpdates for site and web to true, and argument value for BreakRoleInheritance (pass true, if you wan to copy inherited permissions, false if not). SPSecurity.RunWithElevatedPrivileges is used to elevate user context (not needed if code is executed inside workflow).Removing permissions for user or group is quite the same:

      public static void RemovePermission(SPListItem item, SPPrincipal principal)
        {

            SPWeb web = item.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite elevatedSite = new SPSite(web.Site.ID))
                {
                    elevatedSite.AllowUnsafeUpdates = true;
                    using (SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID))
                    {
                        elevatedWeb.AllowUnsafeUpdates = true;
                        SPList list = elevatedWeb.Lists[item.ParentList.ID];
                        SPListItem elevatedItem = (item.FileSystemObjectType == SPFileSystemObjectType.Folder) ?
                            list.Folders.GetItemById(item.ID) : list.Items.GetItemById(item.ID);

                        if (!elevatedItem.HasUniqueRoleAssignments)
                        {
                            elevatedItem.BreakRoleInheritance(true);
                        }
                        elevatedItem.RoleAssignments.RemoveById(principal.ID);
                        elevatedSite.AllowUnsafeUpdates = false;
                        elevatedWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
        }


Creating SharePoint custom roles 
programmatically


SharePoint role is set of basic permission. Full list of permissions is following:
ViewListItems // View items in lists, documents in document libraries, and view Web discussion comments.
AddListItems // Add items to lists, add documents to document libraries, and add Web discussion comments.
EditListItems // Edit items in lists, edit documents in document libraries, edit Web discussion comments in documents, and customize Web Part Pages in document libraries.
DeleteListItems // Delete items from a list, documents from a document library, and Web discussion comments in documents.
ApproveItems // Approve a minor version of a list item or document.
OpenItems = // View the source of documents with server-side file handlers.
ViewVersions // View past versions of a list item or document.
DeleteVersions // Delete past versions of a list item or document.
CancelCheckout // Discard or check in a document which is checked out to another user.
ManagePersonalViews // Create, change, and delete personal views of lists.
ManageLists = // Create and delete lists, add or remove columns in a list, and add or remove public views of a list.
ViewFormPages // View forms, views, and application pages, and enumerate lists.
Open = // Allow users to open a Web site, list, or folder to access items inside that container.
ViewPages // View pages in a Web site.
AddAndCustomizePages // Add, change, or delete HTML pages or Web Part Pages, and edit the Web site using a Windows SharePoint Services–compatible editor.
ApplyThemeAndBorder // Apply a theme or borders to the entire Web site.
ApplyStyleSheets // Apply a style sheet (.css file) to the Web site.
ViewUsageData // View reports on Web site usage.
CreateSSCSite // Create a Web site using Self-Service Site Creation.
ManageSubwebs // Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.
CreateGroups // Create a group of users that can be used anywhere within the site collection.
ManagePermissions // Create and change permission levels on the Web site and assign permissions to users and groups.
BrowseDirectories // Enumerate files and folders in a Web site using Microsoft Office SharePoint Designer 2007 and WebDAV interfaces.
BrowseUserInfo // View information about users of the Web site.
AddDelPrivateWebParts // Add or remove personal Web Parts on a Web Part Page.
UpdatePersonalWebParts // Update Web Parts to display personalized information.
ManageWeb // Grant the ability to perform all administration tasks for the Web site as well as manage content. Activate, deactivate, or edit properties of Web site scoped Features through the object model or through the user interface (UI). When granted on the root Web site of a site collection, activate, deactivate, or edit properties of site collection scoped Features through the object model. To browse to the Site Collection Features page and activate or deactivate site collection scoped Features through the UI, you must be a site collection administrator.
UseClientIntegration // Use features that launch client applications; otherwise, users must work on documents locally and upload changes.
UseRemoteAPIs // Use SOAP, WebDAV, or Microsoft Office SharePoint Designer 2007 interfaces to access the Web site.
ManageAlerts // Manage alerts for all users of the Web site.
CreateAlerts // Create e-mail alerts.
EditMyUserInfo // Allows a user to change his or her user information, such as adding a picture.
EnumeratePermissions // Enumerate permissions on the Web site, list, folder, document, or list item
Default roles sometimes are not suitable (e.g. users should create and edit items in SharePoint list, but should not delete them), so you need to create you own roles. Let’s look how to do that programmatically:

SPWeb web = SPContext.Current.Web;
//need to allow unsafe updates
web.AllowUnsafeUpdates = true;
// create role definition object
SPRoleDefinition role = new SPRoleDefinition();
// set new role name
role.Name = "ContributorNoDelere";
//set permissions for new role
role.BasePermissions = SPBasePermissions.ViewListItems |
    SPBasePermissions.AddListItems |
    SPBasePermissions.EditListItems |
    SPBasePermissions.OpenItems |
    SPBasePermissions.ViewVersions |
    SPBasePermissions.ManagePersonalViews |
    SPBasePermissions.ViewFormPages |
    SPBasePermissions.Open |
    SPBasePermissions.ViewPages |
    SPBasePermissions.CreateSSCSite |
    SPBasePermissions.BrowseDirectories |
    SPBasePermissions.BrowseUserInfo |
    SPBasePermissions.AddDelPrivateWebParts |
    SPBasePermissions.UpdatePersonalWebParts |
    SPBasePermissions.UseClientIntegration |
    SPBasePermissions.UseRemoteAPIs |
    SPBasePermissions.CreateAlerts |
    SPBasePermissions.EditMyUserInfo;
if (!web.IsRootWeb)
{
    //if we're not on root web we need to break role inheritance
    web.RoleDefinitions.BreakInheritance(true, true);
}
web.RoleDefinitions.Add(role);// add role
web.Update(); // update web
web.AllowUnsafeUpdates = false;// revert unsafe updates

As you can see it is quite easy, but don’t forget to break role inheritance, if your web inherits roles from parent.

No comments:

Post a Comment