How to set Item Level Permission for SharePoint 2007 (MOSS/WSS) List/Document Library Programmatically (Part 2)

Requirement:

I have a list and have made settings wherein the user can edit only the items created by them and read others data. Now if a person leaves the company all the data created by he/she will become read only to others. There is no apparent OOB way to give permission to any other user to those items at one go. But we can use custom coding and special ability of SharePoint 2007 to set Item level permission for this requirement.

I have created a Custom Web Service to do the trick (From here you will get information about how to implement this web service in SharePoint). And there is a console application to pass the parameters to the Web Service’s web method. You can replace this console app with Windows/Web Form, Web Part etc. Or you can create a custom workflow which will get activated when any user is removed and will call the web service.

Here is the code for the web service:

===================================================

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using Microsoft.SharePoint;

[WebService(Namespace = "https://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService

{

    public Service () {

        //Uncomment the following line if using designed components

        //InitializeComponent();

    }

    [WebMethod]

    public string ItemPermission(string SitePath, string LibName, string OldUser, string NewUser, string email, string name)

    {

        string ReturnVal = "";

        try

        {

            SPSite WebApp = new SPSite(SitePath);

            SPWeb Site = WebApp.OpenWeb();

            SPList list = Site.Lists[LibName];

            SPQuery newSPQuery = new SPQuery();

            newSPQuery.Query = "<Where><Eq><FieldRef Name=\"Author\"/><Value Type=\"User\">" + OldUser + "</Value></Eq></Where>";

            SPListItemCollection listItemCol = list.GetItems(newSPQuery);

            if (listItemCol.Count > 0)

            {

                foreach (SPListItem item in listItemCol)

                {

                    SPRoleDefinition RoleDefinition = Site.RoleDefinitions.GetByType(SPRoleType.Contributor);

                    SPRoleAssignment RoleAssignment = new SPRoleAssignment(NewUser, email, name, "notes");

                    RoleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

                    if (!item.HasUniqueRoleAssignments)

                    {

                        item.BreakRoleInheritance(true);

                    }

                    item.RoleAssignments.Add(RoleAssignment);

                    item.Update();

                }

            }

        }

        catch (Exception ex)

        {

            ReturnVal += "Permission not set, reason: " + ex.Message;

        }

        return ReturnVal;

    }

   

}

===================================================

Here is the code for console application:

Replace the following things:

<sitepath> with the Full URL of the site

<libname> with the list/library name

<domain> with the domain name

<olduser> with the userid who left the company

<newuser> with the userid to whom you want to give permission

<email of new user> self explaning

<name of new user> self explaning

If "<domain>\\<olduser>" does not work try to use the old user’s full name such as “John Smith”.

=====================================================

using System;

using System.Collections.Generic;

using System.Text;

namespace ConsoleApplication1

{

    class Program

    {

        //localhost.Service newService;

        static void Main(string[] args)

        {

            localhost.Service newService = new localhost.Service();

            newService.UseDefaultCredentials = true; //I am assuming an administrator/power user is running this app or use a specific credential here

            string output = newService.ItemPermission("<sitepath>", "<libname>", "<domain>\\<olduser>", "<domain>\\<newuser>", "<email of new user>", "<name of new user>");

            Console.WriteLine(output);

            Console.ReadLine();

        }

    }

}

See also: How to set Item Level Permission for SharePoint 2007 (MOSS/WSS) List/Document Library Programmatically

Comments

  • Anonymous
    February 14, 2008
    PingBack from http://blogs.msdn.com/pranab/archive/2007/07/04/how-to-set-item-level-permission-for-moss-wss-list-document-library-programmatically.aspx

  • Anonymous
    February 14, 2008
    Requirement: I have a list and have made settings wherein the user can edit only the items created by

  • Anonymous
    September 03, 2008
    hi, how could I list all the users from the item-level permissions? I would want to loop through those users, and if i found "admin", i would not break the inheritance for the listitem. do you know how to do this? thanks!

  • Anonymous
    October 09, 2008
    I want to set permission on Field Level. Scenario : I have two fields Title And Name. If it is contributor then he can see both fields. And if he is Approver then he can see both fields but Name Field should be Readonly. So i need to set permission at sharepoint List Field Level. Reply me ASAP. Thanks & Regards Milan Chauhan milanchauhan@live.com

  • Anonymous
    November 05, 2008
    Is this possible to deny the site administrator access to an item by breaking the inheritance? Thanks,

  • Anonymous
    November 23, 2008
    Hi, Above code works fine with groups and without group also, but one problem i have noticed that even if the user is a part of some group after  performing item.RoleAssignments.Add(RoleAssignment) the user is also added on to site out of group.

  • Anonymous
    January 16, 2009
    using System; using System.Collections.Generic; using System.Text; using System.Configuration; using Microsoft.SharePoint; using Microsoft.SharePoint.Security; namespace BreakInheritance {    class Program    {        static void Main(string[] args)        {            string strSiteURL = ConfigurationManager.AppSettings["SiteName"];            SPSite siteColl = new SPSite(strSiteURL);            SPWeb site = siteColl.OpenWeb();            SPDocumentLibrary docLib = (SPDocumentLibrary)site.Lists[ConfigurationManager.AppSettings["ListName"]];            int count = docLib.Items.Count;            try            {                for (int i = 0; i < count; i++)                {                    SPListItem item = docLib.Items[i];                    Console.WriteLine(item.DisplayName);                    if (!item.HasUniqueRoleAssignments)                    {                        item.BreakRoleInheritance(true);                        SPGroupCollection spgroup = site.SiteGroups;                        SPGroup group = spgroup["Performance Appraisal Visitors"];                        SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group);                        SPRoleDefinition roleDefinition = site.RoleDefinitions["Read"];                        roleAssignment.RoleDefinitionBindings.Add(roleDefinition);                        item.RoleAssignments.Add(roleAssignment);                        site.AllowUnsafeUpdates = true;                        item.Update();                        site.AllowUnsafeUpdates = false;                        Console.WriteLine(item.DisplayName + "'s Permissions are Broken");                    }                    else                    {                    }                }                Console.WriteLine("Process Completed.Press Any Key");                Console.ReadLine();            }            catch (Exception ex)            {            }        }    } }

  • Anonymous
    February 12, 2009
    I just wandering is there any solution that needs not using code. Thanks.

  • Anonymous
    April 16, 2009
    Great article, thank you. My question is how to manage permissions by using the Windows Sharepoint Webservices?

  • Anonymous
    May 12, 2009
    it is fine.  but when we use it on multiple upload, it goes down.... event handler does not work during upload multiple file. what is the solution .

  • Anonymous
    June 07, 2009
    "I have a list and have made settings wherein the user can edit only the items created by them and read others data"  - i have same requirement, can you please post the code. Thanks.

  • Anonymous
    October 09, 2009
    The comment has been removed

  • Anonymous
    March 22, 2010
    Hi, I've got a problem with my Sharepoint Event Handler, I have created a simple handler for ItemUpdated event, and did the necessery steps for activating the Features, it is working fine for local Users as well as Adiminitrator Account, but the thing is not working while a domain user acess it, No Event is received. Where I am wrong? 1. Related to any pemission Issue? 2. Any Perticular setup for domain users? Please reply me ASAP..

  • Anonymous
    August 11, 2010
    Hi, I need this part: "I have a list and have made settings wherein the user can edit only the items created by them and read others data." How did you manage to get this functionality? I'm trying to do it with a Event Receiver programatically. Is there a better/easier way of doing it. (sorry im new to sharepoint) Thanks in advance!!! Regards nfxs

  • Anonymous
    February 21, 2011
    item level permissions slows down the site and increases database overhead I have been setting the permissions for a list items when the users try to edit the item But when i have 100 unique items in the list.... for which 100 unique users are there then when i try to break the permission then SharePoint tries to break the permissions and when i add new users then SharePoint not only adds the unique user to the item but also to the parent (as limited access) i.e., the library and the site in which the library is present. This made my doc lib consist 100 users having limited access and when i try to create new item then all these 100 limited access users are getting permissions for the new item and then i am manually breaking the role inheritance and removing all the users for the item. This not only has made the site performance slower but also the SharePoint log is growing exponentially..... Could any one try to provide solution for this please...... Regards Shiva Komuravelly krishna.bunny@gmail.com