Itle in english: set Item Level Permission for SharePoint (MOSS/WSS) List/Document Library Programmatically
Sometimes, we need to set special permissions for a file in the document library. This permission does not inherit from the list permission. Of course, it is easiest to create a list and store the relevant files, this is achieved, but it will bring about a lot of redundancy. Although the sharepoint user permission system is powerful, its minimum granularity is only at the list level. Therefore, it is necessary to study the permissions smaller than the list level.
In sharepoint, the system's built-in permissions can be described. The blue line indicates that our listitem actually inherits the list permission system, so all its read and write permissions are the same.
The blue line indicates that our listitem actually inherits the list permission system, so all its read and write permissions are the same. This will cause a problem, that is, if we need to set specific permissions for a specific project in the list due to business logic, this built-in permission system cannot meet the requirements. In fact, this requirement is still quite extensive, not because I or someone imagined it out of thin air. The permissions we discuss here can be expressed by our red line, set an Independent Permission System for each listitem.
To implement the listitem Independent Permission System, we must first break down the inheritance. Fortunately, the related interfaces provided by Microsoft allow us to complete this work.
Use the code SPListItem. BreakRoleInheritance (true); then our permission logic diagram can be used to describe.
Well, the constraint has been broken. Next we will look for an entry point to implement our functions. loading our permission code as appropriate can achieve the correct effect, in order to find this correct, we must first understand the creation process of listitem and intuitively describe the events triggered when listitem is added.
Here we use the ItemUpdated event to complete our functions and bind a processing logic for this event. For simplicity, I only provide the logic section here. When the ItemUpdated event occurs, you can call the code to implement the listitem-level permission system.
Use the code to set Item-level permissions for sharepoint/MOSS. The Code is as follows: public string ItemPermission (string SitePath)
{
String ReturnVal = "";
Try
{
SPSite WebApp = new SPSite (SitePath );
SPWeb Site = WebApp. OpenWeb ();
SPList list = Site. Lists ["TestDocLib"];
SPListItem item = list. Items [0];
SPRoleDefinition RoleDefinition = Site. RoleDefinitions. GetByType (SPRoleType. Contributor );
SPRoleAssignment RoleAssignment = new SPRoleAssignment ("<domain >\\ <user>", "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;
}
Item. BreakRoleInheritance (true); this code is the essence.
Well, our requirements are fast and satisfying, but don't be so happy first. There is another very important problem that we haven't solved, that is, how to transfer permissions.
We have set the item-level permissions. You can imagine that in this permission system, if the only person with the modification permission leaves, all others will be read-only, god, how much is the loss of one person's departure in our company. As developers, we must solve such catastrophic problems at the beginning of system establishment. Below I provide a solution to batch transfer our Permissions
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;
}
}
How to use it?
The following shows a console program that describes how to use this webservice.
Replace the following string
<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. usedefacrecredentials = 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 ();
}
}
}
Note: All the code described in this article is tightly coupled with the user. That is to say, the user is stuck in the Code. To meet the actual needs, you must remove this coupling, MOSS/Sharepoint control view page access permission development issues (code method) This article is an example, you can use the same method to create a list, in this way, user coupling is reduced and can be customized by the customer.
Add permissions to items directly, for example, edit permissions.
Item. DoesUserHavePermissions (SPBasePermissions. RditListItems)
Another example is from the Internet:
PSite site = listEvent. site; SPWeb = site. openWeb (); string urlVal = listEvent. webUrl + "/" + listEvent. urlAfter; SPFile file = web. getFile (listEvent. urlAfter); while (file. checkOutStatus! = SPFile. SPCheckOutStatus. None) {file = web. GetFile (listEvent. UrlAfter);} SPListItem myItem = file. Item; // cancel inheritance if (! MyItem. hasUniqueRoleAssignments) myItem. breakRoleInheritance (true); // clear the permission foreach (SPRoleAssignment roleAssignment in myItem. roleAssignments) {roleAssignment. roleDefinitionBindings. removeAll (); roleAssignment. update ();} SPGroup groupAdmin = web. siteGroups ["Project Management System Administrator"]; SPRoleDefinition RoleDefContributor = web. roleDefinitions. getByType (SPRoleType. contributor); SPRoleDefinition RoleDefAdministrator = web. roleDefinitions. getByType (SPRoleType. administrator); SPRoleAssignment RoleAssAdmin = new SPRoleAssignment (SPPrincipal) groupAdmin); SPRoleAssignment RoleAssAuthor = new SPRoleAssignment (SPPrincipal) file. author); RoleAssAdmin. roleDefinitionBindings. add (RoleDefAdministrator); RoleAssAuthor. roleDefinitionBindings. add (RoleDefContributor); // re-assign permissions to myItem. roleAssignments. add (RoleAssAdmin); myItem. update (); myItem. roleAssignments. add (RoleAssAuthor); myItem. update (); using (SPWeb oParentWebsite = SPContext. current. site. allWebs ["Site_Name"]) {SPWebCollection collWebsites = oParentWebsite. webs; SPUser oUser = oParentWebsite. users ["User_Name"]; foreach (SPWeb oWebsite in collWebsites) {SPRole oRole = oWebsite. roles ["Role_Name"]; oRole. removeUser (oUser); oWebsite. dispose ();}}
Reprinted: http://www.cnblogs.com/Creator/archive/2010/12/21/1909393.html