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 = "http://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 (15)

  1. Shiva Komuravelly says:

    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

  2. nfxs says:

    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

  3. Subhadip Goswami says:

    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..

  4. axeion says:

    I am trying to embed .swf file into my webpage under one of the web parts.

    My site is saved under the folder pages in the document library, and I have set the permissions to public viewing for this site. I now have a new folder called venn that contains my .swf file. The properties of my subfolder venn are inherited from it's parent pages. so even my venn folder should be accessible publicly. But when I embed it into my html page and try to open my webpage, it asks for a login authentication, which is only set for private pages. How can change the permissions for the flash file. I was having the same issue previously with one more webpage inside a subfolder, but i corrected it by publishing the webpage, but how can i do the same for the flash file and the .js file.

  5. Muthu says:

    "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.

  6. Saurabh Jain says:

    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 .

  7. Labcleaner says:

    Great article, thank you.

    My question is how to manage permissions by using the Windows Sharepoint Webservices?

  8. brad says:

    I just wandering is there any solution that needs not using code.

    Thanks.

  9. Cheeli.Satish says:

    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)

               {

               }

           }

       }

    }

  10. Vikram says:

    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.

  11. Manju says:

    Is this possible to deny the site administrator access to an item by breaking the inheritance?

    Thanks,

  12. Milan Chauhan says:

    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

  13. jeiku says:

    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!

  14. Requirement: I have a list and have made settings wherein the user can edit only the items created by

Skip to main content