SharePoint Event Receiver ItemAdded assign permission
Hi,
Sometimes we want to remove permissions and only assign permission to the user who uploaded the document in the document library.
Here is the snippet:
HTH,
Andreas
Sometimes we want to remove permissions and only assign permission to the user who uploaded the document in the document library.
Here is the snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | public override void ItemAdded(SPItemEventProperties properties) { if (properties.ListTitle == "My Doc Lib" ) { //we need to check it in otherwise you will get Value Outside Range error properties.ListItem.File.CheckIn(String.Empty); SPSecurity.RunWithElevatedPrivileges( delegate { using (SPSite site = new SPSite(properties.WebUrl)) { using (SPWeb web = site.OpenWeb()) { try { SPList list = web.Lists[properties.ListId]; SPListItem item = list.Items[properties.ListItem.UniqueId]; if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance( false , true ); SPUser user = web.SiteUsers[properties.UserLoginName]; SPRoleDefinition roleDefinition = web.RoleDefinitions[ "My Role" ]; Security.AssignPermissionsToItem(item, user, roleDefinition); } } catch (Exception ex) { properties.Status = SPEventReceiverStatus.CancelWithError; properties.ErrorMessage = "Error : " + ex.Message; } } } }); } } private void AssignPermissionsToItem(SPSecurableObject item, SPPrincipal obj, SPRoleDefinition roleDefinition) { SPRoleAssignment roleAssignment = new SPRoleAssignment(obj); roleAssignment.RoleDefinitionBindings.Add(roleDefinition); item.RoleAssignments.Add(roleAssignment); } |
HTH,
Andreas
Comments
Post a Comment