private void LockCaseSite(SPListItem caseItem, SPWeb caseWeb, DbAdapter dbAdapter) { CreateSPObjPermSProc sProc; if (caseItem != null) { // Record permissions of the Case list item sProc = new CreateSPObjPermSProc(caseWeb.Site.ID, caseWeb.ID, caseItem.ParentList.ParentWeb.ID, caseItem.ParentList.ID, caseItem.UniqueId, caseItem.RoleAssignments.Xml); dbAdapter.ExecuteNonQueryStoredProcedure(sProc); // Reset permissions of case list item and reconfigure SPUser assignedTo, supervisor; GetAssignedToAndSupervisor(caseItem, out assignedTo, out supervisor); caseItem.ResetRoleInheritance(); LockItemPermissions(caseItem, caseWeb, assignedTo, supervisor); } // Record the permissions of the case web sProc = new CreateSPObjPermSProc(caseWeb.Site.ID, caseWeb.ID, null, null, null, caseWeb.RoleAssignments.Xml); dbAdapter.ExecuteNonQueryStoredProcedure(sProc); caseWeb.RecordPermissions(caseWeb, dbAdapter); // Reset permissions of case web and reconfigure caseWeb.ResetRoleInheritance(); // Recursively redefine all object permissions and force them to inherit parent caseWeb.BreakRoleInheritance(false); // Break at web level and redefine permissions from top->down caseWeb.TryGrantPermission(caseWeb.AssociatedOwnerGroup, SPRoleType.Administrator); caseWeb.TryGrantPermission(caseWeb.AssociatedMemberGroup, SPRoleType.Reader); caseWeb.TryGrantPermission(caseWeb.AssociatedVisitorGroup, SPRoleType.Reader); caseWeb.Update(); }
private static void CopyPermissionsForLanguage(SPWeb englishSite, string language, SPSite site) { try { string languageURL = englishSite.ServerRelativeUrl.Replace("CONNECT", language); SPWeb langWeb = SiteExists(site.Url, languageURL); if (langWeb != null) { using (langWeb) { langWeb.AllowUnsafeUpdates = true; langWeb.BreakRoleInheritance(true); CleanUpExistingGroups(langWeb); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" >> copying english permissions to: " + langWeb.Url); foreach (SPRoleAssignment assignment in englishSite.RoleAssignments) { CopyPermission(langWeb, assignment); } //langWeb.SiteLogoUrl = site.Url + englishSite.SiteLogoUrl; //langWeb.Update(); langWeb.AllowUnsafeUpdates = false; } } } catch (Exception ex) { Console.WriteLine("Site does not exist at - " + englishSite.ServerRelativeUrl.Replace("CONNECT", language)); } }
private void CreateSubSiteGroup(SPWeb web, string groupName, SPRoleType roleType, string groupDescription) { var groupInSite = GroupExistsInSiteCollection(web, groupName); if (!groupInSite) { web.AllowUnsafeUpdates = true; web.Update(); web.BreakRoleInheritance(false); SPGroupCollection groups = web.SiteGroups; //for (int i = 0; i < web.SiteAdministrators.Count; i++) //{ // SPUser owner = web.SiteAdministrators[i]; // SPMember member = web.SiteAdministrators[i]; //} SPUser owner = web.SiteAdministrators[0]; SPMember member = web.SiteAdministrators[0]; groups.Add(groupName, member, owner, groupDescription); SPGroup newSPGroup = groups[groupName]; SPRoleDefinition role = web.RoleDefinitions.GetByType(roleType); SPRoleAssignment roleAssignment = new SPRoleAssignment(newSPGroup); roleAssignment.RoleDefinitionBindings.Add(role); web.RoleAssignments.Add(roleAssignment); web.Update(); } }
private void ApplyPermissionForWeb(PermissionEntity pentity, SPWeb web) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { SPUtility.ValidateFormDigest(); using (SPSite elevatedSite = new SPSite(web.Site.ID)) { using (SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID)) { if (pentity.PermissionType == "Inherit") { if (!elevatedWeb.IsRootWeb) { elevatedWeb.ResetRoleInheritance(); } } else if (pentity.PermissionType == "Unique") { if (!elevatedWeb.IsRootWeb) { elevatedWeb.BreakRoleInheritance(false); } ClearPermissions(elevatedWeb); DeleteAllGroupsAndUsers(elevatedWeb); foreach (RoleEntity rentity in pentity.Roles) { if (rentity.Type == RoleTypeEnum.SharePointGroup) { DeleteGroup(elevatedWeb, rentity.AssignmentName); CreateGroup(elevatedWeb, rentity.AssignmentName, rentity.Owner); AddUsersToGroup(elevatedWeb, rentity.AssignmentName, rentity.Users); AssignPermissionLevels(elevatedWeb, rentity.AssignmentName, rentity.PermissionLevels); } else if ((rentity.Type == RoleTypeEnum.DomainGroup) || (rentity.Type == RoleTypeEnum.User)) { AssignPermissionLevelsToNonSharePointGroup(elevatedWeb, rentity.AssignmentName, rentity.PermissionLevels); } } } } } }); } catch (Exception ex) { SquadronContext.HandleException(ex); } }
// Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSecurity.RunWithElevatedPrivileges(delegate() { SPWeb curWeb = (SPWeb)properties.Feature.Parent; //Create full matser page URL Uri masterUri = new Uri(curWeb.Url + "/_catalogs/masterpage/TOSRPMaster.master"); Uri systemMasterUri = new Uri(curWeb.Url + "/_catalogs/masterpage/TOSRPMaster.master"); curWeb.MasterUrl = systemMasterUri.AbsolutePath.Replace("%20", " "); curWeb.CustomMasterUrl = masterUri.AbsolutePath.Replace("%20", " "); curWeb.SiteLogoUrl = new Uri(curWeb.Url + "/_layouts/15/images/arKMedes/TOS/OnboardingLogo.png").AbsolutePath; curWeb.Update(); //create groups string[] groupNames = { "ERS", "INFRA", "NewVista", "KO", "Others", "SI&Apps" }; SPUser _SPUser = curWeb.EnsureUser("SharePoint\\system"); SPMember groupOwner = _SPUser; SPUser defaultUser = _SPUser; try { curWeb.AllowUnsafeUpdates = true; foreach (string groupName in groupNames) { if (!curWeb.HasUniqueRoleAssignments) { // Removing any existing permissions from Site curWeb.BreakRoleInheritance(false); //curWeb.Update(); } int Count = curWeb.SiteGroups.OfType <SPGroup>().Count(g => g.Name.Equals(groupName)); if (Count == 0) { if (groupName == "KO") { string strDesc = "Use " + groupName + " group to give people Full Control permissions for this site"; CreateGroup(curWeb, groupOwner, defaultUser, groupName, strDesc, SPRoleType.Administrator); } else { string strDesc = "Use " + groupName + " group to give people Read permissions for this site"; CreateGroup(curWeb, groupOwner, defaultUser, groupName, strDesc, SPRoleType.Reader); } } } curWeb.AllowUnsafeUpdates = false; } catch (Exception ex) { throw ex; } //CreateSiteNavigation(properties); }); }
public static void BreakRoleInheritance(SPWeb web, bool copyRoleAssigements) { if (web.IsRootWeb) { return; } web.BreakRoleInheritance(copyRoleAssigements); if (!web.HasUniqueRoleDefinitions) { web.RoleDefinitions.BreakInheritance(false, copyRoleAssigements); } }
public static void AddDefaultGroups(SPWeb spWeb, bool copyUsersFromParent) { spWeb.BreakRoleInheritance(false); SPGroup owners = AddGroup(spWeb, DefaultGroups.Owners, copyUsersFromParent); SPGroup members = AddGroup(spWeb, DefaultGroups.Members, copyUsersFromParent); SPGroup vistors = AddGroup(spWeb, DefaultGroups.Vistors, copyUsersFromParent); //SPGroup myGroup = AddGroup(spWeb, "My Group", "An example group.", null, null, null, false); SetAssociatedGroups(spWeb, new[] { owners, members, vistors }); }
private void SetBaseLinePermissions(SPWeb web, SPGroup group) { if (ClearInheritedPermissions) { web.ResetRoleInheritance(); } if (!web.HasUniqueRoleAssignments) { web.BreakRoleInheritance(!ClearInheritedPermissions); } SPGroup existingGroup = GetWebGroup(web); if (existingGroup != null) { web.Groups.Remove(existingGroup.Name); } }
private void ResetWebInheritance(SPWeb web, bool makeInherit) { SPWeb elevatedWeb = null; try { SPSecurity.RunWithElevatedPrivileges(delegate() { SPUtility.ValidateFormDigest(); using (SPSite elevatedSite = new SPSite(web.Site.ID)) { using (elevatedWeb = elevatedSite.OpenWeb(web.ID)) { elevatedWeb.AllowUnsafeUpdates = true; if (makeInherit) { elevatedWeb.ResetRoleInheritance(); } else { elevatedWeb.BreakRoleInheritance(false); } elevatedWeb.Update(); elevatedWeb.AllowUnsafeUpdates = false; } } }); } catch (Exception ex) { SquadronContext.HandleException(ex); } finally { if (elevatedWeb != null) { elevatedWeb.Dispose(); } } }
private void AddGroupRole(SPWeb web, string groupNames, string ouGuid) { SPGroup group = null; try { SPUser user = web.Author; foreach (string groupName in groupNames.Split(';')) { if (!IsExistGroup(web, groupName)) { //web.AllowUnsafeUpdates = true; web.SiteGroups.Add(groupName, user, null, ouGuid);//新建组 if (IsExistGroup(web, groupName)) { group = web.SiteGroups.GetByName(groupName); //改变站点继承权 if (!web.HasUniqueRoleAssignments) { web.BreakRoleInheritance(true); } //组权限分配与定义(New) SPRoleDefinitionCollection roleDefinitions = web.RoleDefinitions; SPRoleAssignmentCollection roleAssignments = web.RoleAssignments; SPMember memCrossSiteGroup = web.SiteGroups[groupName]; SPPrincipal myssp = (SPPrincipal)memCrossSiteGroup; SPRoleAssignment myroles = new SPRoleAssignment(myssp); SPRoleDefinitionBindingCollection roleDefBindings = myroles.RoleDefinitionBindings; roleDefBindings.Add(roleDefinitions["Read"]); roleAssignments.Add(myroles); } //web.AllowUnsafeUpdates = false; } } } catch (Exception) { } }
static void BreakInheritanceAndDeletePermissions(SPWeb web, SPList ccpList, SPListItem eventLogItem) { try { //Ensure Web Permissions are broken web.BreakRoleInheritance(true); //Delete Site Permissions SPRoleAssignmentCollection roleAssignments = web.RoleAssignments; for (int i = roleAssignments.Count - 1; i >= 0; i--) { web.RoleAssignments.Remove(0); } } catch (Exception e) { //Log eventLogItem["Site"] = "Client Permission Error: " + e.Message; eventLogItem.Update(); } }//BreakInheritanceAndDeletePermissions
public static void CreateSiteBySiteTemplate(string url, string webName, string webDescription, string templateName) { string loginName = GetLoginAccountWithDomain; SPSecurity.RunWithElevatedPrivileges(delegate() { SPSite site = new SPSite(SPContext.Current.Site.Url); SPWeb web = site.OpenWeb(); web.AllowUnsafeUpdates = true; //= "subsite1";//创建后的站点是:http://moss:5001/subsite1 if (!web.Webs[webName].Exists) { //1.根据网站模版,创建网站 //= "SubSiteTemplate";//网站模版定义 SPWebTemplate CustomTemplate = null; SPWebTemplateCollection subWebTemplate = web.GetAvailableWebTemplates((uint)web.Locale.LCID); foreach (SPWebTemplate template in subWebTemplate) { if (template.Title == templateName) { CustomTemplate = template; break; } } SPWeb NewWeb = web.Webs.Add(url, webName, webDescription, (uint)2052, CustomTemplate, true, false); NewWeb.AllowUnsafeUpdates = true; //2.给创建好的网站分配权限, //2.1断开网站权限 NewWeb.BreakRoleInheritance(false); //2.2添加网站的"完全控制"权限. SPUser user = web.EnsureUser(loginName); SPRoleAssignment MyRoleAssignment = new SPRoleAssignment(user); MyRoleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions.GetByType(SPRoleType.Administrator)); NewWeb.RoleAssignments.Add(MyRoleAssignment); NewWeb.Update(); } web.Update(); web.Dispose(); }); }
public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPWeb web = properties.Feature.Parent as SPWeb; web.BreakRoleInheritance(false); //remove the groups from the collection string[] groupsNames = new string[web.Groups.Count]; for (int i = 0; i < web.Groups.Count; i++) { groupsNames[i] = web.Groups[i].Name; } for (int j = 0; j < groupsNames.Length; j++) { web.Groups.Remove(groupsNames[j]);; } web.Update(); //add the site groups AddGroup(web, visitor, "Use this group to give people read permissions to the SharePoint site: "); AddGroup(web, member, "Use this group to give people contribute permissions to the SharePoint site: "); AddGroup(web, owner, "Use this group to give people full control permissions to the SharePoint site: "); //add the site groups to the cross site groups web.Roles[readPer].AddGroup(web.SiteGroups[web.ParentWeb.Title + " " + web.Title + visitor]); web.Roles[contributePer].AddGroup(web.SiteGroups[web.ParentWeb.Title + " " + web.Title + member]); web.Roles[adminPer].AddGroup(web.SiteGroups[web.ParentWeb.Title + " " + web.Title + owner]); //add the site groups to the site association web.AssociatedMemberGroup = web.SiteGroups[web.ParentWeb.Title + " " + web.Title + member]; web.AssociatedOwnerGroup = web.SiteGroups[web.ParentWeb.Title + " " + web.Title + owner]; web.AssociatedVisitorGroup = web.SiteGroups[web.ParentWeb.Title + " " + web.Title + visitor]; //update the web object web.Update(); }
/// <summary> /// Grants permissions to a group for a specific site. /// </summary> /// <param name="spGroup">Represents a SharePoint group</param> /// <param name="sPRoleType">Represents the permission to grant to the target group.</param> /// <param name="spWeb">Represents an instance of the Homework Tracking Site as a SPWeb object.</param> private static void GrantGroupSiteLevelPermissions(SPGroup spTargetGroup, SPRoleType sPRoleType, SPWeb spWeb) { if (!spWeb.IsRootWeb) { if (spWeb.HasUniqueRoleAssignments == false) { spWeb.BreakRoleInheritance(true); } /* Adding the School Administration group. */ spWeb.RoleAssignments.Remove(spTargetGroup); SPRoleAssignment roleAssign = new SPRoleAssignment(spTargetGroup); SPRoleDefinition roleDef = spWeb.RoleDefinitions.GetByType(sPRoleType); roleAssign.RoleDefinitionBindings.Add(roleDef); spWeb.RoleAssignments.Add(roleAssign); } }
private void SetUpDocumentWorkspace(SPItemEventProperties eventProperties, SPSite rootWeb, SPWeb documentWorkspace) { //First change the permissions for the documentWorkspace documentWorkspace.AllowUnsafeUpdates = true; documentWorkspace.BreakRoleInheritance(false); string agendaType = eventProperties.ListItem["AgendaType"].ToString(); string agmOffice = eventProperties.ListItem["AGM Office"].ToString(); try { SPFieldUserValueCollection authUsers = PaperLessBoardHelper.GetKeyPeopleForAgenda(agendaType, agmOffice, eventProperties); foreach (SPFieldUserValue userValue in authUsers) { SPRoleAssignment role; role = new SPRoleAssignment(eventProperties.Web.EnsureUser(userValue.LookupValue)); role.RoleDefinitionBindings.Add(documentWorkspace.RoleDefinitions.GetByType(SPRoleType.Contributor)); documentWorkspace.RoleAssignments.Add(role); documentWorkspace.Update(); } //In addition the following groups get certain permissions //TODO: These permissions should ideally come from configuration SPGroup agendaCoordinators = eventProperties.Web.Groups["Agenda Coordinators"]; SPRoleDefinition roleDefForAgendaCoordinators = eventProperties.Web.RoleDefinitions["Read"]; SPRoleAssignment roleForAgendaCoordinators = new SPRoleAssignment(agendaCoordinators); roleForAgendaCoordinators.RoleDefinitionBindings.Add(roleDefForAgendaCoordinators); documentWorkspace.RoleAssignments.Add(roleForAgendaCoordinators); documentWorkspace.Update(); SPGroup emisPortalMembers = eventProperties.Web.Groups["EMIS Portal Members"]; SPRoleDefinition roleDefForEmisPortalMembers = eventProperties.Web.RoleDefinitions["Restricted Contribute"]; SPRoleAssignment roleForEmisPortalMembers = new SPRoleAssignment(emisPortalMembers); roleForEmisPortalMembers.RoleDefinitionBindings.Add(roleDefForEmisPortalMembers); documentWorkspace.RoleAssignments.Add(roleForEmisPortalMembers); documentWorkspace.Update(); SPGroup boardOfficeMembers = eventProperties.Web.Groups["Board Office Members"]; SPRoleDefinition roleDefForBoardOfficeMemebers = eventProperties.Web.RoleDefinitions["Full Control"]; SPRoleAssignment roleForBoardOfficeMembers = new SPRoleAssignment(boardOfficeMembers); roleForBoardOfficeMembers.RoleDefinitionBindings.Add(roleDefForBoardOfficeMemebers); documentWorkspace.RoleAssignments.Add(roleForBoardOfficeMembers); documentWorkspace.Update(); SPGroup cpmManagers = eventProperties.Web.Groups["CPM Managers"]; SPRoleDefinition roleDefForCPMManagers = eventProperties.Web.RoleDefinitions["Restricted Contribute"]; SPRoleAssignment roleForCPMManagers = new SPRoleAssignment(cpmManagers); roleForCPMManagers.RoleDefinitionBindings.Add(roleDefForCPMManagers); documentWorkspace.RoleAssignments.Add(roleForCPMManagers); documentWorkspace.Update(); } catch (Exception exc) { Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Exception – {0} – {1} – {2}", "Board Agenda Receiver Error while adding Key People and setting Permissions in workspace", exc.Message, exc.StackTrace); } //Make sure it inherits the theme from the rootWeb string currentTheme = rootWeb.RootWeb.Theme; documentWorkspace.ApplyTheme(currentTheme); string docSetName = "Agenda Workspace DS-6"; string defaultDocumentsLibraryName = null; string libraryNameInDocumentWorkspace = null; string boardSiteURL = null; string boardMeetingListName = null; string lookAheadListName = null; string masterKeyPeopleListName = null; SPContentType newDocumentSetContentType = null; //SPFolder defaultDocuments =rootWeb.RootWeb.Folders["Default Documents"]; SPWebApplication webApplication = eventProperties.Web.Site.WebApplication; if (webApplication.Properties != null && webApplication.Properties.Count > 0) { if (webApplication.Properties.ContainsKey("DefaultDocumentsLibrary")) { defaultDocumentsLibraryName = webApplication.Properties["DefaultDocumentsLibrary"].ToString(); libraryNameInDocumentWorkspace = webApplication.Properties["LibraryNameInDocumentWorkspace"].ToString(); boardSiteURL = webApplication.Properties["BoardSiteURL"].ToString(); boardMeetingListName = webApplication.Properties["BoardMeetingListName"].ToString(); lookAheadListName = webApplication.Properties["LookAheadListName"].ToString(); lookAheadListName = webApplication.Properties["LookAheadListName"].ToString(); masterKeyPeopleListName = webApplication.Properties["MasterKeyPeopleListName"].ToString(); } } DocumentSetTemplate newDocumentSetTemplate = null; if (eventProperties.ListItem["AgendaType"].ToString() == "Procurement Resolution") { docSetName = DocSetNames.ProcurementResolution; if (rootWeb.RootWeb.ContentTypes[docSetName] == null) { // create the new document set content Type newDocumentSetContentType = rootWeb.RootWeb.ContentTypes.Add(new SPContentType(rootWeb.RootWeb.ContentTypes["Document Set"], rootWeb.RootWeb.ContentTypes, docSetName)); // get a document set template for the new document set newDocumentSetTemplate = DocumentSetTemplate.GetDocumentSetTemplate(newDocumentSetContentType); //add allowable content types newDocumentSetTemplate.AllowedContentTypes.Add(rootWeb.RootWeb.ContentTypes["AgendaDocument"].Id); newDocumentSetTemplate.AllowedContentTypes.Add(rootWeb.RootWeb.ContentTypes["Procurement Resolution"].Id); newDocumentSetTemplate.AllowedContentTypes.Remove(rootWeb.RootWeb.ContentTypes["Document"].Id); newDocumentSetTemplate.Update(true); //make sure to add the document set name to the default documents. newDocumentSetTemplate.DefaultDocuments.AddSetName = false; newDocumentSetTemplate.Update(true); newDocumentSetContentType.Update(); rootWeb.RootWeb.Update(); } } else if (eventProperties.ListItem["AgendaType"].ToString() == "Non-Procurement Resolution") { docSetName = DocSetNames.NonProcurementResolution; if (rootWeb.RootWeb.ContentTypes[docSetName] == null) { // create the new document set content Type newDocumentSetContentType = rootWeb.RootWeb.ContentTypes.Add(new SPContentType(rootWeb.RootWeb.ContentTypes["Document Set"], rootWeb.RootWeb.ContentTypes, docSetName)); // get a document set template for the new document set newDocumentSetTemplate = DocumentSetTemplate.GetDocumentSetTemplate(newDocumentSetContentType); //add allowable content types newDocumentSetTemplate.AllowedContentTypes.Add(rootWeb.RootWeb.ContentTypes["AgendaDocument"].Id); newDocumentSetTemplate.AllowedContentTypes.Remove(rootWeb.RootWeb.ContentTypes["Document"].Id); newDocumentSetTemplate.DefaultDocuments.AddSetName = false; newDocumentSetTemplate.Update(true); newDocumentSetContentType.Update(); rootWeb.RootWeb.Update(); } } else if (eventProperties.ListItem["AgendaType"].ToString() == "Other Matters") { docSetName = DocSetNames.OtherMatters; if (rootWeb.RootWeb.ContentTypes[docSetName] == null) { // create the new document set content Type newDocumentSetContentType = rootWeb.RootWeb.ContentTypes.Add(new SPContentType(rootWeb.RootWeb.ContentTypes["Document Set"], rootWeb.RootWeb.ContentTypes, docSetName)); // get a document set template for the new document set newDocumentSetTemplate = DocumentSetTemplate.GetDocumentSetTemplate(newDocumentSetContentType); //add allowable content types newDocumentSetTemplate.AllowedContentTypes.Add(rootWeb.RootWeb.ContentTypes["AgendaDocument"].Id); newDocumentSetTemplate.AllowedContentTypes.Remove(rootWeb.RootWeb.ContentTypes["Document"].Id); newDocumentSetTemplate.DefaultDocuments.AddSetName = false; newDocumentSetTemplate.Update(true); newDocumentSetContentType.Update(); rootWeb.RootWeb.Update(); } } else if (eventProperties.ListItem["AgendaType"].ToString() == "Briefing") { docSetName = DocSetNames.Briefing; if (rootWeb.RootWeb.ContentTypes[docSetName] == null) { // create the new document set content Type newDocumentSetContentType = rootWeb.RootWeb.ContentTypes.Add(new SPContentType(rootWeb.RootWeb.ContentTypes["Document Set"], rootWeb.RootWeb.ContentTypes, docSetName)); // get a document set template for the new document set newDocumentSetTemplate = DocumentSetTemplate.GetDocumentSetTemplate(newDocumentSetContentType); //add allowable content types newDocumentSetTemplate.AllowedContentTypes.Add(rootWeb.RootWeb.ContentTypes["AgendaDocument"].Id); newDocumentSetTemplate.AllowedContentTypes.Remove(rootWeb.RootWeb.ContentTypes["Document"].Id); newDocumentSetTemplate.DefaultDocuments.AddSetName = false; newDocumentSetTemplate.Update(true); newDocumentSetContentType.Update(); rootWeb.RootWeb.Update(); } } else if (eventProperties.ListItem["AgendaType"].ToString() == "Meeting Minutes") { docSetName = DocSetNames.MeetingMinutes; if (rootWeb.RootWeb.ContentTypes[docSetName] == null) { // create the new document set content Type newDocumentSetContentType = rootWeb.RootWeb.ContentTypes.Add(new SPContentType(rootWeb.RootWeb.ContentTypes["Document Set"], rootWeb.RootWeb.ContentTypes, docSetName)); // get a document set template for the new document set newDocumentSetTemplate = DocumentSetTemplate.GetDocumentSetTemplate(newDocumentSetContentType); //add allowable content types newDocumentSetTemplate.AllowedContentTypes.Add(rootWeb.RootWeb.ContentTypes["AgendaDocument"].Id); newDocumentSetTemplate.AllowedContentTypes.Remove(rootWeb.RootWeb.ContentTypes["Document"].Id); newDocumentSetTemplate.DefaultDocuments.AddSetName = false; newDocumentSetTemplate.Update(true); newDocumentSetContentType.Update(); rootWeb.RootWeb.Update(); } } newDocumentSetContentType = newDocumentSetContentType ?? rootWeb.RootWeb.ContentTypes[docSetName]; documentWorkspace.AllowUnsafeUpdates = true; SPDocumentLibrary list = (SPDocumentLibrary)documentWorkspace.Lists[libraryNameInDocumentWorkspace]; list.ContentTypes.Add(newDocumentSetContentType); foreach (SPContentType defaultContentType in list.ContentTypes) { if (defaultContentType.Name != newDocumentSetContentType.Name) list.ContentTypes.Delete(list.ContentTypes[defaultContentType.Name].Id); } list.EnableVersioning = true; //list.EnableMinorVersions = true; list.MajorVersionLimit = 40; //list.MajorWithMinorVersionsLimit = 12; list.Update(); SPField fldAgendaID = list.Fields.CreateNewField(SPFieldType.Text.ToString(), "AgendaID"); SPField fldPublishToBoard = list.Fields.CreateNewField(SPFieldType.Boolean.ToString(), "PublishToBoard"); SPField fldSponsor = list.Fields.CreateNewField(SPFieldType.User.ToString(), "Sponsor"); list.Fields.Add(fldAgendaID); list.Fields.Add(fldPublishToBoard); list.Fields.Add(fldSponsor); list.Update(); //SPView defaultView = list.Views["All Documents"]; //SPViewFieldCollection viewFields = defaultView.ViewFields; //viewFields.Add(list.Fields["PublishDocumentToBoard"]); //defaultView.Update(); System.Collections.Hashtable properties = new System.Collections.Hashtable(); properties.Add("DocumentSetDescription", string.Format("Document Set for {0}", eventProperties.ListItem["Title"].ToString()) ); //Internal Name properties.Add("_Title", eventProperties.ListItem["Title"].ToString()); //Internal Name properties.Add("PublishToBoard", false); //Default Value is false properties.Add("AgendaID", eventProperties.ListItemId); properties.Add("Sponsor", eventProperties.Web.CurrentUser); //Creating the document set Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet documentSet = Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.Create(list.RootFolder, "Board Agenda Document Set", //string.Format("{0}", eventProperties.ListItem["Title"].ToString()), list.ContentTypes.BestMatch(newDocumentSetContentType.Id), properties, true); string docSetHomePageURL = documentSet.WelcomePageUrl.Substring(0, documentSet.WelcomePageUrl.IndexOf("&RootFolder")); eventProperties.ListItem["DocumentWorkspace"] = string.Format("{0}, {1}", docSetHomePageURL, "Document Workspace"); //Now add the default documents to the library eventProperties.ListItem.Update(); SPQuery queryForDefaultDocs = new SPQuery() { Query = string.Format(@"<Where> <Eq> <FieldRef Name='Agenda Type'/> <Value Type='Choice'>{0}</Value> </Eq> </Where>", eventProperties.ListItem["AgendaType"].ToString()) }; SPDocumentLibrary defaultDocsLibrary = (SPDocumentLibrary)eventProperties.Web.Lists[defaultDocumentsLibraryName]; //SPListItemCollection lic = defaultDocsLibrary.GetItems(queryForDefaultDocs); SPListItemCollection lic = defaultDocsLibrary.Items; foreach (SPListItem defaultDocItem in lic) { if (defaultDocItem["Agenda Type"].ToString() == eventProperties.ListItem["AgendaType"].ToString()) { SPFile file = defaultDocItem.File; byte[] defaultDocumentBytes = file.OpenBinary(); //Add the default document SPListItem itemForFile = file.Item; SPFile addedFile = documentSet.Folder.Files.Add(file.Name, defaultDocumentBytes, true); } } //Get the Meeting Workspace Link string meetingWorkspaceURL = null; string meetingTitle = null; string meetingDate = null; SPUser spUser = eventProperties.Web.CurrentUser; // GetSPUser(eventProperties.ListItem, "Created By"); using (SPSite boardSite = new SPSite(boardSiteURL)) using (SPWeb boardWeb = boardSite.OpenWeb()) { SPList meetingsList = boardWeb.Lists[boardMeetingListName]; SPQuery query = new SPQuery() { Query = string.Format(@"<Where> <Eq> <FieldRef Name='ID'/> <Value Type='Number'>{0}</Value> </Eq> </Where>", eventProperties.ListItem["CommitteeMeeting"].ToString()) }; foreach (SPListItem meeting in meetingsList.GetItems(query)) { meetingWorkspaceURL = meeting["Workspace"].ToString(); meetingTitle = meeting["Title"].ToString(); meetingDate = meeting["EventDate"].ToString(); } eventProperties.ListItem["MeetingTitle"] = meetingTitle; eventProperties.ListItem["MeetingDate"] = meetingDate; eventProperties.ListItem.Update(); /* //Also while you have the site already opened, add an item for the AgendaSummary list SPList agendaSummaryList = boardWeb.Lists[lookAheadListName]; SPListItem agendaSummaryItem = agendaSummaryList.Items.Add(); agendaSummaryItem["Board Agenda"] = eventProperties.ListItem["Title"].ToString(); agendaSummaryItem["Board Meeting"] = meetingTitle; agendaSummaryItem["Meeting Date"] = meetingDate; agendaSummaryItem["Agenda Status"] = "Agenda Created"; //TODO: Remove hardcoding for this and make it configurable. agendaSummaryItem["AgendaID"] = eventProperties.ListItemId; agendaSummaryItem["ResponsiblePerson"] = spUser.Name; agendaSummaryItem["Office"] = eventProperties.ListItem["AGM Office"].ToString(); agendaSummaryItem["MeetingWorkspace"] = meetingWorkspaceURL; agendaSummaryItem.Update(); //Also add the same agenda into the Meeting Workspace's Agenda list int agendaOrder = 0; if (eventProperties.ListItem["AgendaOrder"] != null) agendaOrder = int.Parse(eventProperties.ListItem["AgendaOrder"].ToString()); string presenter = string.Empty; if (eventProperties.ListItem["Presenter"] != null) presenter = eventProperties.ListItem["Presenter"].ToString(); AddAgendaToMeetingWorkspace(boardWeb, meetingWorkspaceURL, eventProperties.ListItem["Title"].ToString(), spUser, eventProperties.ListItemId, presenter, agendaOrder); * * */ } SPWorkflowTemplate template = null; SPWorkflowTemplate notifyCoordinatorsWFTemplate = null; SPWorkflowTemplate reviewContentWFTemplate = null; SPWorkflowTemplate digitalSignaturesWFTemplate = null; //Now associate the workflow //Activate all the necessary features on the site documentWorkspace.Features.Add(new Guid("24512e0e-7b03-466e-9209-38b39a51c581")); // Board Agenda Workflows foreach (SPWorkflowTemplate localwfTemplate in documentWorkspace.WorkflowTemplates) { if (localwfTemplate.Name == "BoardAgendaWorkflow") //TODO: This should come from configuration. { template = localwfTemplate; break; } } foreach (SPWorkflowTemplate localwfTemplate in documentWorkspace.WorkflowTemplates) { if (localwfTemplate.Name == "NotifyCoordinatorsWorkflow") //TODO: This should come from configuration. { notifyCoordinatorsWFTemplate = localwfTemplate; break; } } foreach (SPWorkflowTemplate localwfTemplate in documentWorkspace.WorkflowTemplates) { if (localwfTemplate.Name == "Review Agenda Workflow") //TODO: This should come from configuration. { reviewContentWFTemplate = localwfTemplate; break; } } foreach (SPWorkflowTemplate localwfTemplate in documentWorkspace.WorkflowTemplates) { if (localwfTemplate.Name == "Digital Signatures") //TODO: This should come from configuration. { digitalSignaturesWFTemplate = localwfTemplate; break; } } if (template == null) // If the template was not in the document workspace, then check root web for it. { foreach (SPWorkflowTemplate wfTemplate in rootWeb.RootWeb.WorkflowTemplates) { if (wfTemplate.Name == "BoardAgendaWorkflow") //TODO: This should come from configuration. { template = wfTemplate; } } } if (notifyCoordinatorsWFTemplate == null) { foreach (SPWorkflowTemplate wfTemplate in rootWeb.RootWeb.WorkflowTemplates) { if (wfTemplate.Name == "NotifyCoordinatorsWorkflow") //TODO: This should come from configuration. { notifyCoordinatorsWFTemplate = wfTemplate; } } } if (reviewContentWFTemplate == null) { foreach (SPWorkflowTemplate wfTemplate in rootWeb.RootWeb.WorkflowTemplates) { if (wfTemplate.Name == "Review Agenda Workflow") //TODO: This should come from configuration. { reviewContentWFTemplate = wfTemplate; } } } if (digitalSignaturesWFTemplate == null) { foreach (SPWorkflowTemplate wfTemplate in rootWeb.RootWeb.WorkflowTemplates) { if (wfTemplate.Name == "Digital Signatures") //TODO: This should come from configuration. { digitalSignaturesWFTemplate = wfTemplate; } } } //Delete the default task list that is created SPList defaultTaskList = documentWorkspace.Lists["Tasks"]; documentWorkspace.Lists.Delete(defaultTaskList.ID); //After a Document Set is created, Create three lists in this Document Workspace //1. Workflow History //2. Agenda WF Tasks //3. KeyPeople Guid taskListID = documentWorkspace.Lists.Add("Agenda Tasks", "This task list holds all the tasks associated with the Agenda Workflow", rootWeb.RootWeb.ListTemplates["Agenda Tasks"]); //TODO: Get this from configuration. //Guid taskListID = documentWorkspace.Lists.Add("Tasks", "", SPListTemplateType.Tasks); Guid historyListID = documentWorkspace.Lists.Add("Workflow History", "History list used by the Agenda Workflow", SPListTemplateType.WorkflowHistory); Guid keyPeopleListID = documentWorkspace.Lists.Add("Key People", "List of key people associated with this Agenda", rootWeb.RootWeb.ListTemplates["KeyPeopleDefinition"]); SPWorkflowAssociation workflowAssociation = SPWorkflowAssociation.CreateListAssociation(template, "Board Agenda Workflow", documentWorkspace.Lists[taskListID], documentWorkspace.Lists[historyListID]); workflowAssociation.AllowManual = true; workflowAssociation.AutoStartCreate = false; workflowAssociation.AutoStartChange = false; documentSet.ParentList.WorkflowAssociations.Add(workflowAssociation); SPWorkflowAssociation wfAssociationForNotifyCoordinators = SPWorkflowAssociation.CreateListAssociation(notifyCoordinatorsWFTemplate, "Notify Coordinators Workflow", documentWorkspace.Lists[taskListID], documentWorkspace.Lists[historyListID]); wfAssociationForNotifyCoordinators.AllowManual = true; wfAssociationForNotifyCoordinators.AutoStartCreate = false; wfAssociationForNotifyCoordinators.AutoStartChange = false; documentSet.ParentList.WorkflowAssociations.Add(wfAssociationForNotifyCoordinators); SPWorkflowAssociation wfAssociationForReviewContent = SPWorkflowAssociation.CreateListAssociation(reviewContentWFTemplate, "Review Content Workflow", documentWorkspace.Lists[taskListID], documentWorkspace.Lists[historyListID]); wfAssociationForReviewContent.AllowManual = true; wfAssociationForReviewContent.AutoStartCreate = false; wfAssociationForReviewContent.AutoStartChange = false; documentSet.ParentList.WorkflowAssociations.Add(wfAssociationForReviewContent); SPWorkflowAssociation wfAssociationForDigitalSignatures = SPWorkflowAssociation.CreateListAssociation(digitalSignaturesWFTemplate, "Digital Signatures", documentWorkspace.Lists[taskListID], documentWorkspace.Lists[historyListID]); wfAssociationForDigitalSignatures.AllowManual = true; wfAssociationForDigitalSignatures.AutoStartCreate = false; wfAssociationForDigitalSignatures.AutoStartChange = false; documentSet.ParentList.WorkflowAssociations.Add(wfAssociationForDigitalSignatures); SPList AgendaList = documentWorkspace.Lists[taskListID]; AgendaList.EnableAssignToEmail = true; AgendaList.Update(); SPList taskList = documentWorkspace.Lists[taskListID]; taskList.OnQuickLaunch = true; taskList.Update(); SPView defaultView = taskList.Views["All Tasks"]; SPViewFieldCollection viewFields = defaultView.ViewFields; viewFields.Add(taskList.Fields["Comments"]); viewFields.Delete(taskList.Fields["Predecessors"]); viewFields.Delete(taskList.Fields["Description"]); defaultView.Update(); SPList historyList = documentWorkspace.Lists[historyListID]; historyList.OnQuickLaunch = false; historyList.Update(); SPList keyPeopleList = documentWorkspace.Lists[keyPeopleListID]; keyPeopleList.OnQuickLaunch = true; keyPeopleList.Update(); SPList defaultCalendarList = documentWorkspace.Lists["Calendar"]; defaultCalendarList.OnQuickLaunch = false; defaultCalendarList.Update(); AddKeyPeopleToAgenda(rootWeb, documentWorkspace, keyPeopleListID, masterKeyPeopleListName, agendaType, eventProperties.ListItem["AGM Office"].ToString()); string assemblyName = "PaperlessBoard EventHandlers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=072ce623fbaeb261"; keyPeopleList.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, "PaperlessBoard_EventHandlers.KeyPeopleAddedEventReceiver.KeyPeopleAddedEventReceiver"); keyPeopleList.EventReceivers.Add(SPEventReceiverType.ItemDeleted, assemblyName, "PaperlessBoard_EventHandlers.KeyPeopleAddedEventReceiver.KeyPeopleAddedEventReceiver"); keyPeopleList.EventReceivers.Add(SPEventReceiverType.ItemUpdated, assemblyName, "PaperlessBoard_EventHandlers.KeyPeopleAddedEventReceiver.KeyPeopleAddedEventReceiver"); //Remove the Announcements Webpart. SPLimitedWebPartManager webPartManager = documentWorkspace.GetLimitedWebPartManager("Default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); for (int k = 0; k < webPartManager.WebParts.Count; k++) { //get reference to webpart WebPart wp = webPartManager.WebParts[k] as WebPart; //check webpart Title to find webpart which is to be removed if ((wp.Title == "Announcements") || (wp.Title == "Members")) { //delete webpart webPartManager.DeleteWebPart(webPartManager.WebParts[k]); //update spWeb object documentWorkspace.Update(); } } AddWebPartsToWelcomePage(documentWorkspace, documentSet.WelcomePageUrl); try { CleanUpQuickLaunch(documentWorkspace); } catch (Exception ex) { Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Exception – {0} – {1} – {2}", "Error in Agenda Reciever while cleaning up quick launch.", ex.Message, ex.StackTrace); } documentWorkspace.AllowUnsafeUpdates = false; }
/// <summary> /// The function to Break permission of Web /// </summary> /// <param name="web">Current Web</param> /// <param name="copyRoleAssigements">Copy permission of parrent?</param> public static void BreakRoleInheritance(SPWeb web, bool copyRoleAssigements) { if (web.IsRootWeb) { return; } web.BreakRoleInheritance(copyRoleAssigements); if (!web.HasUniqueRoleDefinitions) { web.RoleDefinitions.BreakInheritance(false, copyRoleAssigements); } }
public override void BreakRoleInheritance(bool copyRoleAssignments) { _spWeb.BreakRoleInheritance(copyRoleAssignments); }
public void setSiteSecurity(Project project, string SiteOwnersGroupName, string SiteManagerGroupName, string SiteReadOnlyUsersGroupName, string SiteAdditionalContributorsGroupName) { using (SPWeb web = safelyGetWeb(parentWebUrl, project.ProjectId)) { // break any existing Security role inheritance and don't copy permissions from the parent. web.BreakRoleInheritance(false); // Remove any groups already on the site, start with a clean slate. securityWipe(web); // Create or attach existing Security Groups. #region Logic: Site Owners Group string ownersGroupName = SiteOwnersGroupName; // Generally, the owners group is global to the collection, so check to see if it exists first. // if it doesn't, assume it should be site-specific and prepend Project ID to it. try { SPGroup owners = web.SiteGroups[SiteOwnersGroupName]; // It Existed, add it as is. setupWebUserGroup(web, ownersGroupName, SPRoleType.Administrator); } catch { // It didn't exist. Make a new site-specific group. ownersGroupName = project.ProjectId + " - " + SiteOwnersGroupName; // MC0101019999 - Site Owners setupWebUserGroup(web, ownersGroupName, SPRoleType.Administrator, "Site Owners for " + project.ProjectId); } #endregion #region Logic: Site Manager Group string managerGroupName = project.ProjectId + " - " + SiteManagerGroupName; // MC0101019999 - Site Manager setupWebUserGroup(web, managerGroupName, SPRoleType.Contributor, "This group should contain ONLY ONE " + "user who is designated as the manager of " + project.ProjectId); // Ensure only the current Litigation Manager is placed inside the intended security group. // Reset Site Manager groups which contain more than one person. SPGroup siteManagerGroup = web.SiteGroups[managerGroupName]; siteManagerGroup.AddUser(project.ProjectLeadSPUser); if (siteManagerGroup.Users.Count > 1) { log.addWarning("Conflicting assignments exist in the '" + siteManagerGroup.Name + "' group for site " + project.ProjectId + ". If the matter is currently being reassigned, this is normal. The group membership has been reset to contain only [" + project.ProjectLeadSPUser.Name + "]. Additional participants, (rare), should be added to one of the following security groups:\n\n" + project.ProjectId + " - " + SiteAdditionalContributorsGroupName + " (Contribute Access)\n" + project.ProjectId + " - " + SiteReadOnlyUsersGroupName + " (Read-Only Access)\n" + SiteOwnersGroupName + " (Administrators Only)"); // Empty the group, and put only the site manager back in. emptySPGroup(siteManagerGroup); siteManagerGroup.AddUser(project.ProjectLeadSPUser); } #endregion #region Logic: Read Only Users Group string readOnlyUsersGroupName = project.ProjectId + " - " + SiteReadOnlyUsersGroupName; // MC0101019999 - Read Only Users setupWebUserGroup(web, readOnlyUsersGroupName, SPRoleType.Reader, "This group contains users with Read-Only access to " + project.ProjectId); #endregion #region Logic: Additional Contributors Group string additionalContributorsGroupName = project.ProjectId + " - " + SiteAdditionalContributorsGroupName; // MC0101019999 - Additional Contributors setupWebUserGroup(web, additionalContributorsGroupName, SPRoleType.Contributor, "This group contains users, who, in addition to the Site Manager, can contribute to " + project.ProjectId + ". Use of this group should be limited to rare exceptions where more than one person requires control of the site."); #endregion // Save Changes and close out web.Update(); } }
/// <summary> /// Sets the anonymous access to all authenticated. /// </summary> /// <param name="web">The web.</param> /// <param name="oItem">The o item.</param> /// <param name="user">The user.</param> /// <exception cref="System.Exception"></exception> public static void SetAnonymousAccessToAll(SPWeb web, SPItem oItem, string user) { if (web.Url == "/") return; switch (oItem["VisibleBy"].ToString()) { //SharepointAdminsOnly case "AuthenticatedUsers": // check if it has unique permissions if (!web.HasUniqueRoleAssignments) { //This method breaks the role assignment inheritance //for the list item, and creates unique role assignments //for the list item with the copyRoleAssignments parameter //which specifies whether to copy role assignments from the //parent object and with the clearSubscopes parameter which //specifies whether to clear role assignments from child objects. web.BreakRoleInheritance(true, false); } switch (DetectSiteLanguage(web)) { //pt-PT case 2070: web.Groups["Visualizadores"].Users.Add(user, null, null, null); break; //eng-USA case 1033: web.Groups["Viewers"].Users.Add(user, null, null, null); break; default: throw new Exception("Not Supported Language!"); } break; } }