.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> SharePoint >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Programmatically Setting item permissions for new items

Posted By:volvo       Posted Date: December 11, 2013    Points: 40    Category: SharePoint    URL: http://www.dotnetspark.com  

The code block explains how to make a sharepoint list only show items to the users who wrote the items, and users specified in the item's properties
 

public override void ItemAdded(SPItemEventProperties properties)
        {
            //get the list item that was created
            SPListItem item = properties.ListItem;
            //get the author user who created the task
            SPFieldUserValue valAuthor = new SPFieldUserValue(properties.Web, item["Created By"].ToString());
            //get the "assigned to" user. Note - this will throw an error if the task is not assigned to anyone - implement error handling!
            SPFieldUserValue valAssignedTo = new SPFieldUserValue(properties.Web, item["Assigned To"].ToString());
            //disconnect the security from the list, and delete all permissions
            item.BreakRoleInheritance(false);
            //create the object that will hold the roles for the author user
            SPRoleAssignment authorRole = new SPRoleAssignment(valAuthor.User);
            //create the object that will hold the roles for the assigned to user
            SPRoleAssignment assignedToRoles = new SPRoleAssignment(valAssignedTo.User);

            //get the contribute role from the web. Alternatively use code to create a new role definition with custom permissions.
            SPWeb oWebsite = properties.Web;
            SPRoleDefinitionCollection collRoles = oWebsite.RoleDefinitions;
            SPRoleDefinition oRoleDefinition = collRoles["Contribute"];

            //assign permissions to task author
            authorRole.RoleDefinitionBindings.Add(oRoleDefinition);
            item.RoleAssignments.Add(authorRole);
            //assign permissions to task assignee
            assignedToRoles.RoleDefinitionBindings.Add(oRoleDefinition);
            item.RoleAssignments.Add(assignedToRoles);
            //update the item
            item.Update();
            base.ItemAdded(properties);
        }


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend