Welcome to MSDN Blogs Sign in | Join | Help

Pranab Paul's Blog - SharePoint 2007 (MOSS/WSS 3.0) Development Tips

------------------------------------------Web Parts, Workflow, InfoPath Form Services, Features, Site Definition, Event Receivers, Excel Services, Business Data Catalog (BDC), Search

News

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

Posted: Thursday, February 14, 2008 6:33 PM by pranab

Comments

SHAREPOINTBlogs.com Mirror said:

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

# February 14, 2008 5:13 PM

jeiku said:

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!

# September 3, 2008 9:53 AM

Milan Chauhan said:

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

# October 10, 2008 6:17 AM

Manju said:

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

Thanks,

# November 5, 2008 12:41 PM

Vikram said:

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.

# November 24, 2008 4:04 AM

Cheeli.Satish said:

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)

           {

           }

       }

   }

}

# January 16, 2009 8:59 AM

brad said:

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

Thanks.

# February 12, 2009 8:47 PM

Labcleaner said:

Great article, thank you.

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

# April 17, 2009 5:29 AM

Saurabh Jain said:

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 .

# May 13, 2009 3:11 AM

Muthu said:

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

# June 8, 2009 4:56 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker