protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(__Context.Site.ID)) { using (SPWeb web = site.AllWebs[__Context.Web.ID]) { SPList list = web.Lists[Helper.GetListGuid(__Context, ListId)]; SPListItem item = list.Items.GetItemById(__ListItem); SPRoleDefinition roleDef = web.RoleDefinitions[RoleName]; if (item.HasUniqueRoleAssignments == false) { item.BreakRoleInheritance(true); } AssignRoles(web, item, roleDef); } } }); return(ActivityExecutionStatus.Closed); }
/// <summary> /// 给Item授权 /// </summary> /// <param name="principal"></param> /// <param name="web"></param> /// <param name="ListItem"></param> /// <param name="DelegateName"></param> public static void DelegateForListItem(SPPrincipal principal, SPWeb web, SPListItem ListItem, string DelegateName) { SPSecurity.RunWithElevatedPrivileges(delegate() { try { using (SPSite site = new SPSite(web.Site.ID)) { using (SPWeb _web = site.OpenWeb(web.ServerRelativeUrl)) { SPListItem _listitem = _web.Lists[ListItem.ParentList.ID].GetItemById(ListItem.ID); _web.AllowUnsafeUpdates = true; SPRoleAssignment sra = new SPRoleAssignment(principal); SPRoleDefinition srd = _web.RoleDefinitions[DelegateName]; sra.RoleDefinitionBindings.Add(srd); _listitem.BreakRoleInheritance(true, false); _listitem.RoleAssignments.Add(sra); _listitem.Update(); } } } catch (Exception ex) { } }); }
public static void AddPermissionsToItem(SPWeb web, SPListItem item, Dictionary <SPPrincipal, string[]> assignments) { if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance(false); } while (item.RoleAssignments.Count > 0) { item.RoleAssignments.Remove(0); } foreach (SPPrincipal principal in assignments.Keys) { foreach (string itemAssignment in assignments[principal]) { SPRoleDefinition roleDef = GetPermissionLevel(web, itemAssignment); if (roleDef == null) { continue; } SPRoleAssignment roleAssignment = new SPRoleAssignment(principal); roleAssignment.RoleDefinitionBindings.Add(roleDef); item.RoleAssignments.Add(roleAssignment); } } //item.Update(); }
public static bool SetUserPermission(this SPListItem item, string userName, string permissionLevel) { var isSet = false; try { item.Web.AllowUnsafeUpdates = true; if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance(false, false); } item.Update(); item.Web.Update(); var roleAssignment = new SPRoleAssignment(item.Web.AllUsers[userName]); roleAssignment.RoleDefinitionBindings.Add(item.Web.RoleDefinitions[permissionLevel]); item.RoleAssignments.Add(roleAssignment); item.Update(); item.ParentList.Update(); item.Web.Update(); isSet = true; } catch (Exception ex) { Log.Error(ex); throw new Exception($"SharePointCore: Error on {nameof(SetUserPermission)}", ex); } return(isSet); }
/// <summary> /// This method should be used instead of BreakRoleInheritance(true). /// /// The OOTB method replicates all permissions from the parent, including the "Limited Access" permissions. /// In environments with many users, there can be many of these meaningless permissions, which bloats the /// SharePoint permission tables in SQL. This method reviews all RoleDefinitions in each principal's /// RoleAssignments, stripping "Limited Access", before adding them to the item. /// </summary> /// <param name="item"></param> public static void BreakCopyRoleInheritance(this SPListItem item) { SPRoleAssignmentCollection roleAssignments = item.RoleAssignments; var activeAssignments = from SPRoleAssignment p in roleAssignments where p.RoleDefinitionBindings.Count >= 1 select p; item.BreakRoleInheritance(false); foreach (SPRoleAssignment p in activeAssignments) { SPRoleAssignment assignment = new SPRoleAssignment(p.Member); SPRoleDefinitionBindingCollection bindings = new SPRoleDefinitionBindingCollection(); foreach (SPRoleDefinition roleDef in p.RoleDefinitionBindings) { if (roleDef.Name != "Limited Access") { bindings.Add(roleDef); } } if (bindings.Count > 0) { assignment.ImportRoleDefinitionBindings(bindings); item.RoleAssignments.Add(assignment); } } }
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite sitecollection = new SPSite(Url)) { using (SPWeb web = sitecollection.OpenWeb()) { SPList list = web.Lists[Liste.ToString()]; SPListItem listitem = list.Items.GetItemById(ElementID); if (listitem != null) { if (!listitem.HasUniqueRoleAssignments) { listitem.BreakRoleInheritance(true); } for (int i = listitem.RoleAssignments.Count - 1; i >= 0; i--) { listitem.RoleAssignments.Remove(i); } listitem.Update(); } } } }); return(base.Execute(executionContext)); }
public static void ClearRights(SPListItem item) { SPWeb web = item.Web; bool allowUnsafeUpdates = web.AllowUnsafeUpdates; web.AllowUnsafeUpdates = true; if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance(false); if (web.AssociatedOwnerGroup != null) { var roleAssignment = new SPRoleAssignment(web.AssociatedOwnerGroup); SPRoleDefinition byType = web.RoleDefinitions.GetByType(SPRoleType.Administrator); roleAssignment.RoleDefinitionBindings.Add(byType); item.RoleAssignments.Add(roleAssignment); } } else { const int num = 0x3fffffff; int num2 = (web.AssociatedOwnerGroup != null) ? web.AssociatedOwnerGroup.ID : -1; for (int i = item.RoleAssignments.Count - 1; i >= 0; i--) { int iD = item.RoleAssignments[i].Member.ID; if ((iD != num) && (iD != num2)) { item.RoleAssignments.Remove(i); } } } web.AllowUnsafeUpdates = allowUnsafeUpdates; }
public static void SetReadOnly(SPListItem item, int userId) { SPWeb web = item.Web; bool allowUnsafeUpdates = web.AllowUnsafeUpdates; web.AllowUnsafeUpdates = true; if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance(true); } web.AllowUnsafeUpdates = true; SPRoleAssignmentCollection roleAssignments = item.RoleAssignments; for (int i = roleAssignments.Count - 1; i > -1; i--) { SPRoleAssignment assignment = roleAssignments[i]; if (assignment.Member.ID == userId) { SPRoleDefinitionBindingCollection roleDefinitionBindings = assignment.RoleDefinitionBindings; if ((roleDefinitionBindings.Count != 1) || (roleDefinitionBindings[0].Type != SPRoleType.Reader)) { roleDefinitionBindings.RemoveAll(); SPRoleDefinition byType = web.RoleDefinitions.GetByType(SPRoleType.Reader); roleDefinitionBindings.Add(byType); assignment.Update(); } break; } } web.AllowUnsafeUpdates = allowUnsafeUpdates; }
public static void SetReadOnly(SPListItem item) { SPWeb web = item.Web; bool allowUnsafeUpdates = web.AllowUnsafeUpdates; web.AllowUnsafeUpdates = true; if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance(true); } web.AllowUnsafeUpdates = true; SPRoleAssignmentCollection roleAssignments = item.RoleAssignments; int iD = web.Site.SystemAccount.ID; int num2 = (web.AssociatedOwnerGroup != null) ? web.AssociatedOwnerGroup.ID : -1; for (int i = roleAssignments.Count - 1; i > -1; i--) { SPRoleAssignment assignment = roleAssignments[i]; int num4 = assignment.Member.ID; if ((num4 != iD) && (num4 != num2)) { SPRoleDefinitionBindingCollection roleDefinitionBindings = assignment.RoleDefinitionBindings; if ((roleDefinitionBindings.Count != 1) || (roleDefinitionBindings[0].Type != SPRoleType.Reader)) { roleDefinitionBindings.RemoveAll(); SPRoleDefinition byType = web.RoleDefinitions.GetByType(SPRoleType.Reader); roleDefinitionBindings.Add(byType); assignment.Update(); } } } web.AllowUnsafeUpdates = allowUnsafeUpdates; }
private static void SetFolderPermissions(SPWeb web, string folderName, string memGrpName, string visGrpName, string blackbeltGroupName, string greenbeltGroupName, SPFolder fldr) { try { SPRoleDefinition pwcContribute = web.RoleDefinitions["PWC Contribute"]; SPRoleDefinition read = web.RoleDefinitions["Read"]; SPRoleDefinition viewOnly = web.RoleDefinitions["View Only"]; SPRoleDefinition pwcBronzeAdmin = web.RoleDefinitions["PWC Bronze Admin"]; SPRoleDefinition fullControl = web.RoleDefinitions["Full Control"]; SPGroup newMemGroup = web.SiteGroups[memGrpName]; SPGroup newVisGroup = web.SiteGroups[visGrpName]; SPGroup BBGroup = web.SiteGroups[blackbeltGroupName]; SPGroup GBGroup = web.SiteGroups[greenbeltGroupName]; SPListItem li = fldr.Item; if (li.Name.Equals(folderName)) { li.BreakRoleInheritance(false); while (li.RoleAssignments.Count > 0) { li.RoleAssignments.Remove(0); } SPRoleAssignment spRoleAssignMemGrp = new SPRoleAssignment(newMemGroup); spRoleAssignMemGrp.RoleDefinitionBindings.Add(pwcContribute); li.RoleAssignments.Add(spRoleAssignMemGrp); SPRoleAssignment spRoleAssignVisGrp = new SPRoleAssignment(newVisGroup); spRoleAssignVisGrp.RoleDefinitionBindings.Add(read); li.RoleAssignments.Add(spRoleAssignVisGrp); SPRoleAssignment spRoleAssignBBGroup = new SPRoleAssignment(BBGroup); spRoleAssignBBGroup.RoleDefinitionBindings.Add(read); li.RoleAssignments.Add(spRoleAssignBBGroup); SPRoleAssignment spRoleAssignGBGroup = new SPRoleAssignment(GBGroup); spRoleAssignGBGroup.RoleDefinitionBindings.Add(read); li.RoleAssignments.Add(spRoleAssignGBGroup); //SPRoleAssignment spRoleAssignBronzeAdminGrp = new SPRoleAssignment(bronzeAdminGroup); //spRoleAssignBronzeAdminGrp.RoleDefinitionBindings.Add(pwcBronzeAdmin); //spRoleAssignBronzeAdminGrp.RoleDefinitionBindings.Add(pwcContribute); // li.RoleAssignments.Add(spRoleAssignBronzeAdminGrp); //SPRoleAssignment spRoleAssignOwnerGrp = new SPRoleAssignment(ownerGroup); //spRoleAssignOwnerGrp.RoleDefinitionBindings.Add(fullControl); // li.RoleAssignments.Add(spRoleAssignOwnerGrp); } } catch (Exception e) { e.Message.ToString(); // ULSLogger.LogErrorInULS("Inside catch in setFolderPermissions() in PWC Secure Folder Feature---" + e.Message); } }
private void ConfigureItemPermissions(SPListItem item, SPWeb caseWeb, SPUser assignedTo, SPUser supervisor) { item.BreakRoleInheritance(false); item.TryGrantPermission(assignedTo, SPRoleType.Administrator); item.TryGrantPermission(supervisor, SPRoleType.Administrator); item.TryGrantPermission(eCaseGroups.GetOwners(caseWeb), SPRoleType.Administrator); item.TryGrantPermission(eCaseGroups.GetParticipants(caseWeb), SPRoleType.Contributor); }
private void CheckFiles(XmlNode siteNode, string url) { bool containsIgnoreInheritance = ContainsAttribute("ignoreinheritance", siteNode); bool containsImportOptions = ContainsAttribute("import", siteNode); bool ignoreInheritance = containsIgnoreInheritance ? Boolean.Parse(siteNode.Attributes["ignoreinheritance"].Value) : true; ImportOptions importOptions = containsImportOptions ? (ImportOptions)Enum.Parse(typeof(ImportOptions), siteNode.Attributes["import"].Value) : ImportOptions.All; if (importOptions == ImportOptions.Folders) { return; } using (SPWeb web = new SPSite(url).OpenWeb()) { XmlNodeList fileNodes = siteNode.SelectNodes("file"); foreach (XmlNode fileNode in fileNodes) { string fileTitle = fileNode.Attributes["file"].Value; string fileUrl = fileNode.Attributes["url"].Value; output.Append(string.Format("checking file: {0}" + Environment.NewLine, fileUrl)); try { SPFile file = web.GetFile(fileUrl); SPListItem item = file.Item; bool breakInheritance = !item.HasUniqueRoleAssignments && !ignoreInheritance; bool applyPermissions = item.HasUniqueRoleAssignments || breakInheritance; if (applyPermissions) { if (breakInheritance) { output.Append(string.Format("Breaking Inheritance!" + Environment.NewLine)); item.BreakRoleInheritance(false, false); } XmlNodeList principalGroupNodes = fileNode.SelectNodes("principal[@Group='true']"); CheckGroups(web, item, principalGroupNodes); XmlNodeList principalUserNodes = fileNode.SelectNodes("principal[@Group='false']"); CheckUsers(web, item, principalUserNodes); } else { output.Append(string.Format("target file: {0,20}, is inheriting permissions" + Environment.NewLine, fileUrl)); } } catch { output.Append(string.Format("file missing: {0,20}" + Environment.NewLine, fileUrl)); } } } }
/// <summary> /// 删除指定角色的权限 /// </summary> /// <param name="principal">角色</param> /// <param name="web"></param> /// <param name="ListItem">item对象</param> /// <param name="DelegateName">权限名称</param> public static void DeleteDelegateFromListItem(SPPrincipal principal, SPWeb web, SPListItem ListItem, string DelegateName) { SPSecurity.RunWithElevatedPrivileges(delegate() { try { if (principal != null) { using (SPSite site = new SPSite(web.Site.ID)) { using (SPWeb _web = site.OpenWeb(web.ServerRelativeUrl)) { SPListItem _listitem = _web.Lists[ListItem.ParentList.ID].GetItemById(ListItem.ID); _web.AllowUnsafeUpdates = true; //断开原来列表项所继承的权限,使其可以设置独立权限 if (!_listitem.HasUniqueRoleAssignments) { _listitem.BreakRoleInheritance(true); } SPRoleAssignment role = _listitem.RoleAssignments.GetAssignmentByPrincipal(principal); if (!string.IsNullOrWhiteSpace(DelegateName)) { SPRoleDefinition def = _web.RoleDefinitions[DelegateName]; if (role != null) { if (role.RoleDefinitionBindings.Contains(def)) { role.RoleDefinitionBindings.Remove(def); role.Update(); _listitem.SystemUpdate(false); } } } else { if (role != null) { role.RoleDefinitionBindings.RemoveAll(); role.Update(); _listitem.SystemUpdate(false); } } } } } else { //throw new Exception("没有可以删除权限的员工或组织!"); } } catch (Exception ex) { } }); }
/// <summary> /// An item was updated /// </summary> public override void ItemUpdated(SPItemEventProperties properties) { if (properties.ListItem["updateContributors"].ToString().Equals("True")) { //work around so it goes through it only once instead of everytime the item is updated properties.ListItem["updateContributors"] = "False"; SPSite site = new SPSite("http://sp2010dev/ardt/"); using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists["Document Collaboration"]; SPListItem listItem = properties.ListItem; SPUser userName = null; String toAddress = null; //EMail initializations bool appendHtmlTag = false; bool htmlEncode = false; string subject = "You have been assigned to a Document"; string message = "Test Message"; //get usernames string tempFieldValue = listItem["Assigned To"].ToString(); string[] userNameArray = listItem["Assigned To"].ToString().Split(';'); //remove permissions first web.AllowUnsafeUpdates = true; listItem.BreakRoleInheritance(false); SPRoleAssignmentCollection raCollection = listItem.RoleAssignments; //remove exisiting permissions one by one for (int a = raCollection.Count - 1; a >= 0; a--) { raCollection.Remove(a); } for (int i = 1; i < userNameArray.Length; i++) { tempFieldValue = userNameArray[i].Replace("#", ""); userName = web.AllUsers[tempFieldValue]; toAddress = userName.Email; SPSecurity.RunWithElevatedPrivileges(delegate() { //EMAIL USER bool result = SPUtility.SendEmail(web, appendHtmlTag, htmlEncode, toAddress, subject, message); //PERMISSIONS //grant permissions for specific list item SPRoleDefinition roleDefintion = web.RoleDefinitions.GetByType(SPRoleType.Contributor); SPRoleAssignment roleAssignment = new SPRoleAssignment(userName); roleAssignment.RoleDefinitionBindings.Add(roleDefintion); listItem.RoleAssignments.Add(roleAssignment); listItem.Update(); }); i++; } } //base.ItemUpdated(properties); //after final update has been done return true properties.ListItem["updateContributors"] = "True"; } }
private void ApplyPermissionForListItem(PermissionEntity pentity, SPListItem item) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { SPUtility.ValidateFormDigest(); using (SPSite elevatedSite = new SPSite(item.ParentList.ParentWeb.Site.ID)) { using (SPWeb elevatedWeb = elevatedSite.OpenWeb(item.ParentList.ParentWeb.ID)) { elevatedWeb.AllowUnsafeUpdates = true; SPList elevatedList = elevatedWeb.Lists[item.ParentList.Title]; SPListItem elevatedListItem = elevatedList.GetItemById(item.ID); if (pentity.PermissionType == "Inherit") { elevatedListItem.ResetRoleInheritance(); } else if (pentity.PermissionType == "Unique") { elevatedListItem.BreakRoleInheritance(false); ClearPermissions(elevatedListItem); foreach (RoleEntity rentity in pentity.Roles) { if (rentity.Type == RoleTypeEnum.SharePointGroup) { // Do not delete as parents may use it, DeleteGroup(list.ParentWeb, rentity.AssignmentName); CreateGroup(elevatedListItem.ParentList.ParentWeb, rentity.AssignmentName, rentity.Owner); AddUsersToGroup(elevatedListItem.ParentList.ParentWeb, rentity.AssignmentName, rentity.Users); AssignPermissionLevels(elevatedListItem, rentity.AssignmentName, rentity.PermissionLevels); } else if ((rentity.Type == RoleTypeEnum.DomainGroup) || (rentity.Type == RoleTypeEnum.User)) { AssignPermissionLevelsToNonSharePointGroup(elevatedListItem, rentity.AssignmentName, rentity.PermissionLevels); } } } } } }); } catch (Exception ex) { SquadronContext.HandleException(ex); } }
public static void RemovePermissions(this SPListItem item, List <SPPrincipal> principalsToRemove) { foreach (SPPrincipal principal in principalsToRemove) { if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance(true); } item.RoleAssignments.Remove(principal); } }
public static void ClearRights(SPWeb web, SPListItem item, bool deleteGuest) { bool allowUnsafeUpdates = web.AllowUnsafeUpdates; web.AllowUnsafeUpdates = true; item.BreakRoleInheritance(true); web.AllowUnsafeUpdates = true; SPRoleAssignmentCollection roleAssignments = item.RoleAssignments; bool flag2 = false; bool flag3 = false; int iD = web.Site.SystemAccount.ID; int num2 = (web.AssociatedOwnerGroup != null) ? web.AssociatedOwnerGroup.ID : -1; for (int i = roleAssignments.Count - 1; i > -1; i--) { SPRoleAssignment assignment = roleAssignments[i]; int num4 = assignment.Member.ID; if (num4 == iD) { flag3 = true; } else if (num4 == num2) { flag2 = true; } else if (deleteGuest) { roleAssignments.Remove(i); } else { assignment.RoleDefinitionBindings.RemoveAll(); assignment.Update(); } } web.AllowUnsafeUpdates = true; SPRoleDefinition byType = web.RoleDefinitions.GetByType(SPRoleType.Administrator); if (!flag3) { var roleAssignment = new SPRoleAssignment(web.Site.SystemAccount); roleAssignment.RoleDefinitionBindings.Add(byType); roleAssignments.Add(roleAssignment); } if (!(flag2 || (web.AssociatedOwnerGroup == null))) { var assignment3 = new SPRoleAssignment(web.AssociatedOwnerGroup); assignment3.RoleDefinitionBindings.Add(byType); roleAssignments.Add(assignment3); } web.AllowUnsafeUpdates = allowUnsafeUpdates; }
public static SPFolder EnsurePersonalFolder(SPWeb site, string listWPpageurl, string username) { if (site == null) { throw new ArgumentException("site"); } if (string.IsNullOrEmpty(listWPpageurl)) { throw new ArgumentException("listWPpageurl"); } if (string.IsNullOrEmpty(username)) { throw new ArgumentException("username"); } string personalFolderUrl = SPUtility.ConcatUrls(site.GetListFromWebPartPageUrl(listWPpageurl).RootFolder.ServerRelativeUrl, username); SPFolder folder = site.GetFolder(personalFolderUrl); if (folder.Item == null) // its strange that for a non-existing folder, folder won't be null, but folder.Item will { folder = site.Folders.Add(personalFolderUrl); } SPListItem folderItem = folder.Item; folderItem["Title"] = username; if (folderItem.HasUniqueRoleAssignments) { folderItem.ResetRoleInheritance(); } //if (!folderItem.HasUniqueRoleAssignments) //TODO: permission level 的名称中英文 { folderItem.BreakRoleInheritance(false); SPRoleAssignment FullControlRoleAssignment = new SPRoleAssignment(site.AssociatedOwnerGroup); FullControlRoleAssignment.RoleDefinitionBindings.Add(site.RoleDefinitions["完全控制"]); folderItem.RoleAssignments.Add(FullControlRoleAssignment); //SPRoleAssignment ReadRoleAssignment = new SPRoleAssignment(w.AssociatedVisitorGroup); //ReadRoleAssignment.RoleDefinitionBindings.Add(w.RoleDefinitions["Read"]); //folderItem.RoleAssignments.Add(ReadRoleAssignment); SPRoleAssignment ownerRoleAssignment = new SPRoleAssignment(site.EnsureUser(string.Concat("i:0#.f|fbamember|", username))); ownerRoleAssignment.RoleDefinitionBindings.Add(site.RoleDefinitions["参与讨论"]); folderItem.RoleAssignments.Add(ownerRoleAssignment); } folderItem.Update(); return(folder); }
private void RemoveAllPermisions(SPListItem currentListItem) { //The below function Breaks the role assignment inheritance for the list and gives the current list its own copy of the role assignments currentListItem.BreakRoleInheritance(true); //Get the list of Role Assignments to list item and remove one by one. SPRoleAssignmentCollection SPRoleAssColn = currentListItem.RoleAssignments; for (int i = SPRoleAssColn.Count - 1; i >= 0; i--) { SPRoleAssColn.Remove(i); } }
private void updateItemPermissions(SPItemEventProperties properties) { try { //temporarely disable item firing so that we do not end in the infinite loop 42: this.EventFiringEnabled = false; SPListItem item = properties.ListItem; // now, get the same item with the elevated privileges // we have to do it that way because we do not know which level of // permissions the current user has SPSecurity.RunWithElevatedPrivileges(delegate() { SPList parentList = item.ParentList; SPSite elevatedSite = new SPSite(parentList.ParentWeb.Site.ID); SPWeb elevatedWeb = elevatedSite.OpenWeb(parentList.ParentWeb.ID); SPList elevatedList = elevatedWeb.Lists[parentList.ID]; // get the file with the privileged permissions SPListItem elevatedItem = elevatedList.Items.GetItemById(properties.ListItem.ID); // break item permissions inheritance and assign new permissions based on //Wenn keine speziellen Berechtigungen auf dieses Item gesetzt sind (Vererbung) ... if (!item.HasUniqueRoleAssignments) { //... durchbrechen wir die Vererbungshierarchie, ohne Berechtigungen zu kopieren item.BreakRoleInheritance(false); } SPUser editor = elevatedWeb.EnsureUser((new SPFieldLookupValue(item["MyEditor"].ToString())).LookupValue); SPUser author = elevatedWeb.EnsureUser((new SPFieldLookupValue(item["MyAuthor"].ToString())).LookupValue); //Erzeugen von Rollendefinition, einmal Leser und einmal Schreibender SPRoleDefinition RoleDefReader = elevatedWeb.RoleDefinitions.GetByType(SPRoleType.Reader); SPRoleDefinition RoleDefWriter = elevatedWeb.RoleDefinitions.GetByType(SPRoleType.Contributor); //Rollenzuweisung: Mitarbeiter bekommt Leserechte, Vorgesetzter und Personalabteilung Schreibrechte SPRoleAssignment RoleAssReader = new SPRoleAssignment((SPPrincipal)editor); SPRoleAssignment RoleAssWriter = new SPRoleAssignment((SPPrincipal)author); //Rollenzuweisung dem ListItem hinzufügen RoleAssReader.RoleDefinitionBindings.Add(RoleDefReader); RoleAssWriter.RoleDefinitionBindings.Add(RoleDefWriter); item.RoleAssignments.Add(RoleAssReader); item.RoleAssignments.Add(RoleAssWriter); item.Update(); }); //enable the event firing again this.EventFiringEnabled = true; } catch (Exception ex) { } }
protected void update_permission(SPItemEventProperties properties, SPUser user) { SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(properties.SiteId)) { using (SPWeb web = site.OpenWeb("/admin")) { SPListItem item = web.Lists[properties.ListId].Items.GetItemById(properties.ListItemId); item.BreakRoleInheritance(false); try { // 清理旧权限。 int role_index = 0; while (item.RoleAssignments.Count > 1) { SPRoleAssignment role = item.RoleAssignments[role_index]; if (role.Member.LoginName.ToLower() == "sharepoint\\system") { role_index++; } else { item.RoleAssignments.Remove(role_index); } } } catch (Exception ex) { log(site, "自动删除项目旧权限", "错误", ex.ToString()); } // 分别为各个角色赋予此项目的独特权限:。 //if (item["_x8bf7__x5047__x5355__x5ba1__x62"]!=null) //{ // string workflow_status = item["_x8bf7__x5047__x5355__x5ba1__x62"].ToString(); // if (workflow_status == "16"||workflow_status=="17") // { // Records.DeclareItemAsRecord(item); // } //} //else //{ assign_role(site, item, user, "", web.RoleDefinitions["参与讨论"]); assign_roles(web, item, "相关经理", "", web.RoleDefinitions["批准"]); //} log(web.Site, "更新项目权限", "消息", "为项目【" + item["Title"] + "】更新权限完成。"); } } }); }
/// <summary> /// Назначить права на элемент /// </summary> /// <param name="item">Элемент</param> public void ApplyPermission(SPListItem item) { item.BreakRoleInheritance(true); if (this.AuthorRoles.Any(x => x.Name.Equals(PortalConstant.Role.Seller, StringComparison.InvariantCulture) || x.Name.Equals(PortalConstant.Role.Responsible, StringComparison.InvariantCulture))) { item.AddPermission(this.Author, this.ElevatedWeb, PortalConstant.Role.Editor); } if (this.AuthorRoles.Any(x => x.Name.Equals(PortalConstant.Role.Lead, StringComparison.InvariantCulture))) { item.AddPermission(this.Author, this.ElevatedWeb, PortalConstant.Role.Archivator); } }
private void ResetItemInheritance(SPListItem listItem, bool makeInherit) { SPWeb elevatedWeb = null; SPList elevatedList = null; SPListItem elevatedListItem = null; try { SPSecurity.RunWithElevatedPrivileges(delegate() { SPUtility.ValidateFormDigest(); using (SPSite elevatedSite = new SPSite(listItem.ParentList.ParentWeb.Site.ID)) { using (elevatedWeb = elevatedSite.OpenWeb(listItem.ParentList.ParentWeb.ID)) { elevatedWeb.AllowUnsafeUpdates = true; elevatedList = elevatedWeb.Lists[listItem.ParentList.Title]; elevatedListItem = elevatedList.GetItemById(listItem.ID); if (makeInherit) { elevatedListItem.ResetRoleInheritance(); } else { elevatedListItem.BreakRoleInheritance(false); } elevatedListItem.Update(); elevatedWeb.AllowUnsafeUpdates = false; } } }); } catch (Exception ex) { SquadronContext.HandleException(ex); } finally { if (elevatedWeb != null) { elevatedWeb.Dispose(); } } }
/// <summary> /// 已添加项. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); if (properties.ListTitle == "请假单审批任务") { Guid related_field_guid = new Guid("{58ddda52-c2a3-4650-9178-3bbc1f6e36da}"); string link = properties.ListItem[related_field_guid].ToString().Split(',')[0]; int id_index = link.IndexOf("ID="); int id = int.Parse(link.Substring(id_index + 3)); SPListItem ask_leave_item = properties.OpenWeb().Lists["请假单"].GetItemById(id); SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(properties.SiteId)) { using (SPWeb web = site.OpenWeb("/admin")) { SPListItem item = web.Lists[properties.ListId].Items.GetItemById(properties.ListItemId); item.BreakRoleInheritance(false); try { // 清理旧权限。 int role_index = 0; while (item.RoleAssignments.Count > 1) { SPRoleAssignment role = item.RoleAssignments[role_index]; if (role.Member.LoginName.ToLower() == "sharepoint\\system") { role_index++; } else { item.RoleAssignments.Remove(role_index); } } foreach (SPRoleAssignment ra in ask_leave_item.RoleAssignments) { item.RoleAssignments.Add(ra); } } catch (Exception ex) { log(site, "自动删除项目旧权限", "错误", ex.ToString()); } // 分别为各个角色赋予此项目的独特权限:。 log(web.Site, "更新项目权限", "消息", "为项目【" + item["Title"] + "】更新权限完成。"); } } }); } }
public static void RemovePermissions(this SPListItem item, string loginName) { if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance(true); } SPPrincipal loginPrincipal = item.Web.Site.FindUserOrSiteGroup(loginName); if (loginPrincipal != null) { item.RoleAssignments.Remove(loginPrincipal); } }
/// <summary> /// Gives a user read access to a file in a SharePoint document library. /// </summary> /// /// <param name="loginName">The login name, e.g. "SlkLearner123".</param> /// /// <param name="packageUrl">The URL of the file to give the user access to. This file must /// exist within a SharePoint document library, and the current user (i.e. the user /// running this program) must have sufficient permissions to grant the specified user /// access to the file.</param> /// static void GiveUserReadAccessToFile(string loginName, string packageUrl) { Stack <IDisposable> disposer = new Stack <IDisposable>(); try { // make <spListItem> refer to the file specified by <packageUrl> SPSite packageSite = new SPSite(packageUrl); disposer.Push(packageSite); SPWeb packageWeb = packageSite.OpenWeb(); disposer.Push(packageWeb); Uri packageUri = new Uri(packageUrl); SPListItem spListItem = packageWeb.GetListItem(packageUri.AbsolutePath); // make <spUser> refer to the user specified by <loginName> SPUser spUser; string domainName = String.Format(@"{0}\{1}", s_parentWeb.Site.HostName, loginName); try { spUser = packageWeb.SiteUsers[domainName]; } catch (SPException) { // if user doesn't exist on <packageWeb>, add them packageWeb.SiteUsers.Add(domainName, String.Empty, String.Empty, String.Empty); spUser = packageWeb.SiteUsers[domainName]; } // if <spListItem> inherits permissions from its parent folder or document library, // break that inheritance if (!spListItem.HasUniqueRoleAssignments) { spListItem.BreakRoleInheritance(true); } // grant <spUser> read access to <spListItem> SPRoleDefinition roleDefinition = packageWeb.RoleDefinitions["Read"]; SPRoleAssignment roleAssignment = new SPRoleAssignment(spUser); roleAssignment.RoleDefinitionBindings.Add(roleDefinition); spListItem.RoleAssignments.Add(roleAssignment); } finally { // dispose of objects used by this method while (disposer.Count > 0) { disposer.Pop().Dispose(); } } }
private void SetPermissionsForAssistant(SPUserCodeWorkflowContext context, string assignedTo, string id, string sourceList) { using (SPSite site = new SPSite(context.CurrentWebUrl)) { using (SPWeb web = site.OpenWeb()) { SPList source = web.Lists[sourceList]; if (source != null) { if (!string.IsNullOrEmpty(assignedTo)) { int itemId; string username = string.Empty; if (int.TryParse(id, out itemId)) { SPListItem item = source.GetItemById(itemId); if (item != null) { isUserAdded = false; if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance(true); } foreach (SPRoleAssignment assignment in item.RoleAssignments) { if (assignment.Member.LoginName == assignedTo && assignment.RoleDefinitionBindings.Contains(web.RoleDefinitions.GetByType(SPRoleType.Contributor))) { isUserAdded = true; //res += "isUserAdded = true"; //debug += "isUserAdded = true"; } } SPPrincipal spPrincipal = GetPrincipal(site, assignedTo); //res += "SPPrincipal: " + spPrincipal.Name; //debug += "SPPrincipal: " + spPrincipal.Name; if (spPrincipal != null) { UpdateItemPermissions(web, item, spPrincipal); } } } } } } } }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { try { SPList spList = properties.List; if (spList.Title.Equals("MSA Schedule")) { SPFieldUrlValue spFieldURL = new SPFieldUrlValue(); spFieldURL.Url = "/sites/ffl/Pages/MSA.aspx?SID=" + properties.ListItemId; spFieldURL.Description = "Please click here"; SPListItem spListItem = properties.ListItem; spListItem["MSAFormLink"] = spFieldURL; SPGroup spGroup = properties.Web.SiteGroups["HSE-FFL"]; SPRoleDefinition spRole = properties.Web.RoleDefinitions["Contribute"]; SPRoleAssignment roleAssignment = new SPRoleAssignment(spGroup); roleAssignment.RoleDefinitionBindings.Add(spRole); if (Convert.ToString(spListItem["FFLEmailAddress"]) != null) { SPUser spUSer = properties.Web.SiteUsers.GetByEmail(Convert.ToString(spListItem["FFLEmailAddress"])); SPRoleDefinition spRole1 = properties.Web.RoleDefinitions["Read"]; SPRoleAssignment roleAssignment1 = new SPRoleAssignment(spUSer); roleAssignment1.RoleDefinitionBindings.Add(spRole1); spListItem.BreakRoleInheritance(false); spListItem.RoleAssignments.Add(roleAssignment); spListItem.RoleAssignments.Add(roleAssignment1); } spListItem.Update(); } else { properties.Status = SPEventReceiverStatus.CancelNoError; } } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("MSAEventReceiver", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace); } finally { base.ItemAdded(properties); } }
private void SetTrainingCourseItemPermission(SPListItem tcItem) { tcItem.BreakRoleInheritance(false); foreach (PickerEntity entity in peAttendees.ResolvedEntities) { SPPrincipal principal = MOSSPrincipal.FindUserOrSiteGroup(entity.Key); SPRoleAssignment roleAssignment = MOSSPermission.GetRoleAssignment(principal, SPRoleType.Reader); tcItem.RoleAssignments.Add(roleAssignment); } SPPrincipal hrPrincipal = MOSSPrincipal.FindUserOrSiteGroup(AnalogicConstant.HR); SPRoleAssignment hrAssign = MOSSPermission.GetRoleAssignment(hrPrincipal, SPRoleType.Contributor); tcItem.RoleAssignments.Add(hrAssign); }
public static void RemoveAllPermissions(this SPListItem item) { //remove all current permissions if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance(false); } else { while (item.RoleAssignments.Count > 0) { item.RoleAssignments.Remove(0); } } }
private string SetListItemPermission(SPListItem Item, int userId, int PermissionID, bool ClearPreviousPermissions) { string strError = ""; string siteURL = Item.ParentList.ParentWeb.Url; Guid listId = Item.ParentList.ID; SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(siteURL)) { using (SPWeb web = site.OpenWeb()) { SPPrincipal byID; Exception exception; web.AllowUnsafeUpdates = true; SPListItem itemById = web.Lists[listId].GetItemById(Item.ID); if (!itemById.HasUniqueRoleAssignments) { itemById.BreakRoleInheritance(!ClearPreviousPermissions); } try { byID = web.SiteUsers.GetByID(userId); } catch (Exception exception1) { exception = exception1; byID = web.SiteGroups.GetByID(userId); } SPRoleAssignment roleAssignment = new SPRoleAssignment(byID); SPRoleDefinition roleDefinition = web.RoleDefinitions.GetById(PermissionID); roleAssignment.RoleDefinitionBindings.Add(roleDefinition); itemById.RoleAssignments.Remove(byID); itemById.RoleAssignments.Add(roleAssignment); try { itemById.SystemUpdate(false); } catch (Exception exception2) { exception = exception2; strError = exception.Message; } } } }); return(strError); }
private void ModifyItemPermissions(SPListItem listItem) { // Modifying the permissions for the list to restrict the students for direct list items operations try { if (!listItem.HasUniqueRoleAssignments) { var web = listItem.ParentList.ParentWeb; listItem.BreakRoleInheritance(false, false); var group = web.SiteGroups[Utilities.FacultyGroupName]; var roleAssignment = new SPRoleAssignment(group); var spRole = web.RoleDefinitions["Full Control"]; roleAssignment.RoleDefinitionBindings.Add(spRole); listItem.RoleAssignments.Add(roleAssignment); roleAssignment = new SPRoleAssignment(SPContext.Current.Web.CurrentUser); spRole = web.RoleDefinitions["Read"]; roleAssignment.RoleDefinitionBindings.Add(spRole); listItem.RoleAssignments.Add(roleAssignment); listItem.Update(); } } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("BethesdaSkillLab", TraceSeverity.Monitorable, EventSeverity.Error), TraceSeverity.Monitorable, ex.Message, new object[] { ex.StackTrace }); } }
/// <summary> /// 取消某个SPListItem从父节点继承的权限 /// </summary> /// <param name="item"></param> public static void BreakAndClearRoleInheritance(SPListItem item) { //item.ParentList.ParentWeb.AllowUnsafeUpdates = true; SPWeb web = item.ParentList.ParentWeb; web.AllowUnsafeUpdates = true ; try { item.BreakRoleInheritance(true); } catch { } web.AllowUnsafeUpdates = true; int count_ra = item.RoleAssignments.Count; // 如果某个RoleAssignment的Member为系统管理员, 则不要删除之 for (int index = count_ra - 1; index >= 0; index--) if (item.RoleAssignments[index].Member.Name.ToLower() != "SHAREPOINT\\system".ToLower()) item.RoleAssignments.Remove(index); }
/// <summary> /// adds a specified role for a given user on a list item /// </summary> /// <param name="web">ref to SPWeb</param> /// <param name="listItem">list item in question</param> /// <param name="role">role to add for user e.g. Contribute, View or any custom permission level</param> /// <param name="loginName">login name of user or sharepoint group</param> /// <returns></returns> internal static SPListItem SetItemPermissions(SPWeb web, SPListItem listItem, string role, string loginName) { if (!listItem.HasUniqueRoleAssignments) { listItem.BreakRoleInheritance(true); } SPRoleDefinition RoleDefinition = web.RoleDefinitions[role]; SPPrincipal myUser = FindUserOrSiteGroup(web.Site, loginName); if (myUser == null) { throw new ArgumentException(string.Format("user:{0} is not a valid sharepoint user!")); } SPRoleAssignment RoleAssignment = new SPRoleAssignment(myUser); RoleAssignment.RoleDefinitionBindings.Add(RoleDefinition); listItem.RoleAssignments.Add(RoleAssignment); return listItem; }
/// <summary> /// removes role assigments for principal, breaking inheritance if specified /// </summary> /// <param name="item"></param> /// <param name="principal"></param> /// <param name="breakRoleInheritance"></param> internal static void RemoveListItemPermissionEntry(SPListItem item, string principalName, bool breakRoleInheritance) { List<int> usersToRemove = new List<int>(); if (!item.HasUniqueRoleAssignments && breakRoleInheritance) item.BreakRoleInheritance(true); else if (!item.HasUniqueRoleAssignments) return; SPPrincipal myPrincipal = FindUserOrSiteGroup(item.Web.Site, principalName); foreach (SPRoleAssignment ra in item.RoleAssignments) { if (ra.Member.ID == myPrincipal.ID) { usersToRemove.Add(ra.Member.ID); } } foreach (int id in usersToRemove) { item.RoleAssignments.RemoveById(id); } }
public static void AssignPermission(SPListItem Item, string LoginName, string UserEmail, string UserNote, string UserName, SPWeb Web) { Web.AllowUnsafeUpdates = true; //Remove all existing RoleAssignments for (int i = Item.RoleAssignments.Count - 1; i >= 0; i--) { Item.RoleAssignments.Remove(Item.RoleAssignments[i].Member); } SPRoleAssignment roleAssignment = new SPRoleAssignment(LoginName, UserEmail, UserName, UserNote); SPRoleDefinition roleDefinition = Web.RoleDefinitions.GetByType(SPRoleType.Administrator); roleAssignment.RoleDefinitionBindings.Add(roleDefinition); if (!Item.HasUniqueRoleAssignments) { // Ensure we don't inherit permissions from parent Item.BreakRoleInheritance(true); } Item.RoleAssignments.Add(roleAssignment); Item.SystemUpdate(false); Web.Update(); Web.AllowUnsafeUpdates = false; }
/// <summary> /// This method assigns user or group with read permission on the current item/file. /// </summary> /// <param name="Item">SPListItem</param> /// <param name="Approver">string</param> /// <param name="Web">SPWeb</param> public static void AssignApproverReadPermission(SPListItem Item,SPUser Approver,SPWeb Web) { bool _roleAssignmentExist = false; //Checking if role already exit for the current user or group. foreach(SPRoleAssignment rs in Item.RoleAssignments) { if (rs.Member == Approver) { _roleAssignmentExist = true; } } //Add user or group role assignment. if (_roleAssignmentExist == false) { SPSecurity.RunWithElevatedPrivileges(delegate() { SPRoleAssignment roleAssignment = new SPRoleAssignment(Approver.LoginName, Approver.Email, Approver.Name, "Approver's file access permission."); SPRoleDefinition roleDefinition = Web.RoleDefinitions.GetByType(SPRoleType.Administrator); roleAssignment.RoleDefinitionBindings.Add(roleDefinition); if (!Item.HasUniqueRoleAssignments) { // Ensure we don't inherit permissions from parent Item.BreakRoleInheritance(true); } Item.Web.AllowUnsafeUpdates = true; Item.RoleAssignments.Add(roleAssignment); Item.SystemUpdate(false); Item.Web.AllowUnsafeUpdates = false; }); } }
/// <summary> /// This method marks the current Item as shared /// </summary> /// <param name="site">SPWeb</param> /// <param name="item">SPListItem</param> /// <param name="Shared">bool</param> public static void ShareItem(SPWeb site, SPListItem item, bool Shared) { item.BreakRoleInheritance(true); site.AllowUnsafeUpdates = true; SPFieldUrlValue value = new SPFieldUrlValue(); //Remove all existing RoleAssignments for (int i = item.RoleAssignments.Count - 1; i >= 0; i--) { item.RoleAssignments.Remove(item.RoleAssignments[i].Member); } if (Shared == true) { SPList siteList = site.Lists["Shared Documents"]; for (int i = siteList.RoleAssignments.Count - 1; i >= 0; i--) { item.RoleAssignments.Add(siteList.RoleAssignments[i]); } value.Description = "Shared"; value.Url = SPHelper.GetRootUrl(SPContext.Current.Web.Url) + "_layouts/IMAGES/sharedoc.gif"; } else { value.Description = "Private"; value.Url = SPHelper.GetRootUrl(SPContext.Current.Web.Url) + "_layouts/IMAGES/bizdataactionicon.gif"; } item["Access Level"] = value; item.Update(); site.AllowUnsafeUpdates = false; site.Update(); }
public static void CopyListItemRoleAssignments(SPListItem sourceListItem, SPListItem destinationListItem) { //First check if the Source List has Unique permissions if (sourceListItem.HasUniqueRoleAssignments) { //Break List permission inheritance first destinationListItem.BreakRoleInheritance(true); destinationListItem.Update(); //Remove current role assignemnts while (destinationListItem.RoleAssignments.Count > 0) { destinationListItem.RoleAssignments.Remove(0); } destinationListItem.Update(); //Copy Role Assignments from source to destination list. foreach (SPRoleAssignment sourceRoleAsg in sourceListItem.RoleAssignments) { SPRoleAssignment destinationRoleAsg = null; //Get the source member object SPPrincipal member = sourceRoleAsg.Member; //Check if the member is a user try { SPUser sourceUser = (SPUser)member; SPUser destinationUser = destinationListItem.ParentList.ParentWeb.AllUsers[sourceUser.LoginName]; if (destinationUser != null) { destinationRoleAsg = new SPRoleAssignment(destinationUser); } } catch { } //Not a user, try check if the member is a Group if (destinationRoleAsg == null) { //Check if the member is a group try { SPGroup sourceGroup = (SPGroup)member; SPGroup destinationGroup = destinationListItem.ParentList.ParentWeb.SiteGroups[sourceGroup.Name]; if (destinationGroup != null) { destinationRoleAsg = new SPRoleAssignment(destinationGroup); } } catch { } } //At this state we should have the role assignment established either by user or group if (destinationRoleAsg != null) { foreach (SPRoleDefinition sourceRoleDefinition in sourceRoleAsg.RoleDefinitionBindings) { try { destinationRoleAsg.RoleDefinitionBindings.Add(destinationListItem.ParentList.ParentWeb.RoleDefinitions[sourceRoleDefinition.Name]); } catch { } } if (destinationRoleAsg.RoleDefinitionBindings.Count > 0) { //handle additon of an existing permission assignment error try { destinationListItem.RoleAssignments.Add(destinationRoleAsg); } catch (ArgumentException) { } } } } //Ensure item update metadata is not affected. destinationListItem.SystemUpdate(false); } else //No need to assign permissions return; }
/// <summary> /// 为某个SPPrincipal赋于针对某个SPListItem的权限. 权限由rd来决定. /// </summary> /// <param name="item">某个需要赋于权限的SPListItem</param> /// <param name="spPrincipalName">用户登录名称或者是MOSS User Group, 如果是EMail地址, 则略过</param> /// <param name="rd">需要赋于的权限级别名称</param> public static void AddRoleAssignmentToListItem(SPListItem item, string spPrincipalName, SPRoleDefinition rd) { // 表明这个LoginName是电子邮件地址类型:SmtpAddress if (spPrincipalName.IndexOf("@") >= 0) return; SPRoleAssignment ra = null; // 如果spPrincipalName里面包含\, 则表示是一个AccountId, 否则是一个SPGroup if (spPrincipalName.IndexOf("\\") >= 0) ra = new SPRoleAssignment(spPrincipalName, string.Empty, string.Empty, string.Empty); else { try { SPGroup group = item.Web.Groups[spPrincipalName]; if (group != null) { ra = new SPRoleAssignment(group); } } catch { } } if (ra == null) return; SPRoleDefinition rd_temp = null; // 特别处理的地方:rd在创建并添加到Web.RoleDefinitions之后, 还不能直接使用rd这个变量,可能是复制了一个副本,然后再添加到Collection中去的,所以这里需要从Collection中查找副本, 然后再对其进行引用 // 不可以直接写为: ra.RoleDefinitionBindings.Add(rd) ; 会报错称不能使用Web中未定义的RD // 这个问题的本质原因在于创建类RoleDefinition之后, 前面拿到的SPWeb不会同步更新, 重新打开SPWeb就可以解决问题 for (int index = 0; index < item.Web.RoleDefinitions.Count; index++) if (item.Web.RoleDefinitions[index].Name.ToLower() == rd.Name.ToLower()) rd_temp = item.Web.Site.RootWeb.RoleDefinitions[index]; ra.RoleDefinitionBindings.Add(rd_temp); item.BreakRoleInheritance(false); item.RoleAssignments.Add(ra); }
public static void UpdateGroupPermission(SPWeb web, bool isBreakRole, SPListItem item, string Group, string RoleDefinition) { web.AllowUnsafeUpdates = true; if (isBreakRole) { item.ResetRoleInheritance(); item.Update(); if (!item.HasUniqueRoleAssignments) item.BreakRoleInheritance(false); } SPRoleDefinition SPRoleDefinitionData = item.Web.RoleDefinitions[RoleDefinition]; string[] GroupSplit = Group.Split(';'); foreach (string i in GroupSplit) { SPGroup MembersGroup = item.Web.SiteGroups[i]; SPRoleAssignment MembersRoleAssignment = new SPRoleAssignment(MembersGroup); MembersRoleAssignment.RoleDefinitionBindings.Add(SPRoleDefinitionData); item.RoleAssignments.Add(MembersRoleAssignment); } item.Update(); }
public static void UpdateUserPermission(SPWeb web, bool isBreakRole, SPListItem item, string LoginName, string RoleDefinition) { web.AllowUnsafeUpdates = true; if (isBreakRole) { item.ResetRoleInheritance(); item.Update(); if (!item.HasUniqueRoleAssignments) item.BreakRoleInheritance(false); } SPRoleDefinition SPRoleDefinitionData = item.Web.RoleDefinitions[RoleDefinition]; string[] split = LoginName.Split(';'); foreach (string s in split) { SPRoleAssignment RoleAssignment = new SPRoleAssignment(s, string.Empty, string.Empty, string.Empty); RoleAssignment.RoleDefinitionBindings.Add(SPRoleDefinitionData); item.RoleAssignments.Add(RoleAssignment); } item.Update(); }