You are on page 1of 7

using using using using using using using using using using

System; System.Collections.Generic; System.Text; System.Globalization; System.Configuration; System.Web; Microsoft.Office.Server; Microsoft.Office.Server.UserProfiles; Microsoft.SharePoint; Microsoft.SharePoint.Utilities;

using System.IO; namespace PIMS_Portfolio_Creation { class AutomationManager { /// <summary> /// Create a SharePoint site /// </summary> /// <param name="siteUrl">a site url under which to create the new site< /param> /// <param name="tempalteName">The template name to use to create the si te. The template name must include .stp</param> /// <param name="siteCollectionAdminName">The name of the site collectio n administrator name</param> /// <param name="siteName">The name of the new site to be created</param > /// <param name="title">The title of the new site</param> /// <param name="description">The description of the new site</param> public static void CreateSite(string siteUrl, string templateName, strin g siteCollectionAdminName, string siteName, string title, string description) { // open the site without passing the admin token. the current logged on windows user is used. SPUserToken adminUserToken = GetUserToken(siteUrl, siteCollectionAdm inName); if (adminUserToken == null) { // Could not find Site collection admin's token. return; } using (SPSite site = new SPSite(siteUrl, adminUserToken)) { //allow update without securiry validation site.AllowUnsafeUpdates = true; //add a new spweb in the allweb collection of the current SPSite SPWeb web; switch (templateName) { case "Portfolio.stp": { web = site.AllWebs.Add(siteName, title, description, 1033, templateName, true, false); AddGroups(web, false); // Break inheritance for Working Documents document library

SPList DLWorking = web.Lists["Working Documents"]; DLWorking.BreakRoleInheritance(true); RemovePermission(DLWorking, "Project Initiative Mana gement System Visitors", "Read"); // Break inheritance for eMail document library SPList DLeMail = web.Lists["eMail"]; DLeMail.BreakRoleInheritance(true); // Remove user permissions RemovePermission(DLeMail, "Project Initiative Manage ment System Visitors", "Read"); web.Dispose(); break; } case "Event.stp": { web = site.AllWebs.Add(siteName, title, description, 1033, templateName, false, false); web.Dispose(); break; } case "Note.stp": { web = site.AllWebs.Add(siteName, title, description, 1033, templateName, false, false); // Break inheritance for Posts list SPList DLPosts = web.Lists["Posts"]; DLPosts.BreakRoleInheritance(true); // Remove user permissions RemovePermission(DLPosts, "Project Initiative Manage ment System Visitors", "Read"); // Remove users from portfolio site web.Dispose(); break; } } } } private static SPUserToken GetUserToken(string siteUrl, string userName) { SPUserToken userToken = null; using (SPSite site = new SPSite(siteUrl)) { // an SCA member must create the site. // Cycle through all SPWeb users until the logged on user is fou nd. foreach (SPUser user in site.RootWeb.AllUsers) { string siteUserName = user.LoginName; // Parse out the user name to the right of the :. if (user.LoginName.IndexOf(':') != -1) { string[] DomainAndUser = user.LoginName.Split(new char[] { ':' }); siteUserName = DomainAndUser[1]; } else if (user.LoginName.IndexOf('\\') != -1) { // Parse out the username. string[] DomainAndUser = user.LoginName.Split(new char[]

{ '\\' }); siteUserName = DomainAndUser[1]; } if (siteUserName == userName) { userToken = user.UserToken; break; } } } return userToken; } public enum AssociatedGroupTypeEnum { SiteOwners, Owners, Members, Visto rs }; public static void AddGroups(SPWeb spWeb, bool copyUsersFromParent) { spWeb.BreakRoleInheritance(true); SPGroup SiteOwners = AddGroup(spWeb, AssociatedGroupTypeEnum.SiteOwn ers, true); SPGroup Owners = AddGroup(spWeb, AssociatedGroupTypeEnum.Owners, cop yUsersFromParent); SPGroup members = AddGroup(spWeb, AssociatedGroupTypeEnum.Members, c opyUsersFromParent); SPGroup vistors = AddGroup(spWeb, AssociatedGroupTypeEnum.Vistors, t rue); SetAssociatedGroups(spWeb, new SPGroup[] { SiteOwners, Owners, membe rs }); } public static void SetAssociatedGroups(SPWeb spWeb, SPGroup[] groups) { string formatString = ""; object[] ids = new object[groups.Length]; for (int i = 0; i < groups.Length; i++) { formatString += string.Format("{{{0}}};", i); ids[i] = groups[i].ID; } spWeb.Properties["vti_associategroups"] = string.Format(formatString .TrimEnd(new char[] { ';' }), ids); spWeb.Properties.Update(); } public static SPGroup AddGroup(SPWeb spWeb, AssociatedGroupTypeEnum asso ciateGroupType, bool copyUsersFromParent) { SPGroup group; SPRoleAssignment roleAssignment; SPRoleDefinition roleDefinition; switch (associateGroupType) { case AssociatedGroupTypeEnum.SiteOwners: group = spWeb.SiteGroups["Project Initiative Management Syst em Owners"]; roleAssignment = new SPRoleAssignment(group); roleDefinition = spWeb.RoleDefinitions["Full Control"]; roleAssignment.RoleDefinitionBindings.Add(roleDefinition); spWeb.RoleAssignments.Add(roleAssignment);

return group; case AssociatedGroupTypeEnum.Owners: return AddGroup(spWeb, spWeb.Name + " Owners", "Use this gro up to give full control to the portfolio: {0}", "Contribute", "vti_associatemembergroup", spWeb.ParentWeb.AssociatedMe mberGroup, true); case AssociatedGroupTypeEnum.Members: return AddGroup(spWeb, spWeb.Name + " Members", "Use this gr oup to give permissions to contibute to the portfolio: {0}", "Contribute", "vti_associatemembergroup", spWeb.ParentWeb.AssociatedMe mberGroup, copyUsersFromParent); case AssociatedGroupTypeEnum.Vistors: group = spWeb.SiteGroups["Project Initiative Management Syst em Visitors"]; roleAssignment = new SPRoleAssignment(group); roleDefinition = spWeb.RoleDefinitions["Read"]; roleAssignment.RoleDefinitionBindings.Add(roleDefinition); spWeb.RoleAssignments.Add(roleAssignment); return group; default: return null; } } public static SPGroup AddGroup(SPWeb spWeb, string groupName, string des criptionFormatString, string roleDefinitionName, string associatedGroupName, SPGroup parentAssociatedGroup, bool copyUsersFromParent) { SPGroup owner = parentAssociatedGroup; if (associatedGroupName != "vti_associateownergroup") owner = spWeb.SiteGroups.GetByID(3); spWeb.SiteGroups.Add(groupName, owner, null, string.Format(descripti onFormatString, spWeb.Name)); SPGroup group = spWeb.SiteGroups[groupName]; if (descriptionFormatString.IndexOf("{0}") != -1) { SPListItem item = spWeb.SiteUserInfoList.GetItemById(group.ID); item["Notes"] = string.Format(descriptionFormatString, string.Fo rmat("<a href=\"{0}\">{1}</a>", spWeb.Url, spWeb.Name)); item.Update(); } if (roleDefinitionName != null) { SPRoleAssignment roleAssignment = new SPRoleAssignment(group); SPRoleDefinition roleDefinition = spWeb.RoleDefinitions[roleDefi nitionName]; roleAssignment.RoleDefinitionBindings.Add(roleDefinition); spWeb.RoleAssignments.Add(roleAssignment); } if (copyUsersFromParent && parentAssociatedGroup != null) foreach (SPUser user in parentAssociatedGroup.Users) group.AddUser(user); if (associatedGroupName != null) { spWeb.Properties[associatedGroupName] = group.ID.ToString(); spWeb.Properties.Update(); } spWeb.Update(); return group; }

public static void RemovePermission(SPList list, string groupName, strin g permissionName) { try { SPPrincipal userGroup = FindUserOrSiteGroup(list.ParentWeb.Site, groupName); SPRoleAssignment spRoleAssign = list.RoleAssignments.GetAssignme ntByPrincipal(userGroup); SPRoleDefinition role = list.ParentWeb.RoleDefinitions[permissio nName]; spRoleAssign.RoleDefinitionBindings.Remove(role); //spRoleAssign.RoleDefinitionBindings.Add(role); spRoleAssign.Update(); list.Update(); } catch { } } private static SPPrincipal FindUserOrSiteGroup(SPSite site, string userO rGroup) { SPPrincipal myUser = null; if (SPUtility.IsLoginValid(site, userOrGroup)) { myUser = site.RootWeb.EnsureUser(userOrGroup); } else { //might be a group foreach (SPGroup g in site.RootWeb.SiteGroups) { if (g.Name.ToUpper(CultureInfo.InvariantCulture) == userOrGr oup.ToUpper(CultureInfo.InvariantCulture)) { myUser = g; break; } } } return myUser; } static void RemoveUserFromSiteCollectionByUserName(string siteUrl, strin g userName, SPWeb web) { SPUser user = web.SiteUsers[userName]; if (!user.IsDomainGroup && !user.IsSiteAdmin) { web.SiteUsers.Remove(user.LoginName); web.Update(); } } public static void InsertPortfolioListItem(string sPIMSPortfolioListURL, string sPortfolioName, string sPortfolioDescription, string sPortfolioOwnersGro up) {

using (SPSite site = new SPSite(sPIMSPortfolioListURL)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists["Portfolio"]; SPListItem Item = list.Items.Add(); Item["Name"] = sPortfolioName; Item["Status"] = "Active"; Item["Description"] = sPortfolioDescription; Item.Update(); RemoveAllListPermissions(Item); SPPrincipal userGroupSiteOwners = FindUserOrSiteGroup(list.P arentWeb.Site, "Project Initiative Management System Owners"); GrantListPermission(Item, web, SPRoleType.Contributor, userG roupSiteOwners); SPPrincipal userGroupVisitors = FindUserOrSiteGroup(list.Par entWeb.Site, "Project Initiative Management System Visitors"); GrantListPermission(Item, web, SPRoleType.Reader, userGroupV isitors); // Assign Portfolio Owners - No Delete to the new Portfolio Owner's group. SPPrincipal userGroupOwners = FindUserOrSiteGroup(list.Paren tWeb.Site, sPortfolioOwnersGroup); AssignCustomListPermissionLevel(Item, web, userGroupOwners); } } } private static void RemoveAllListPermissions(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 on e. SPRoleAssignmentCollection SPRoleAssColn = CurrentlistItem.RoleAssig nments; for (int i = SPRoleAssColn.Count - 1; i >= 0; i--) { SPRoleAssColn.Remove(i); } } private static void GrantListPermission(SPListItem CurrentListItem, SPWe b oSPWeb, SPRoleType SPRoleType, SPPrincipal SPPrincipal) { //Create the Role Definition. SPRoleDefinition oSPRoleDefinition = oSPWeb.RoleDefinitions.GetByTyp e(SPRoleType); //Create the Role Assignment for the specified SP user or group. SPRoleAssignment oSPRoleAssignment = new SPRoleAssignment(SPPrincipa l); //Bind the role definition to the role assignment for the group. oSPRoleAssignment.RoleDefinitionBindings.Add(oSPRoleDefinition); //Add it to the specified list item. CurrentListItem.RoleAssignments.Add(oSPRoleAssignment); //update the list item. CurrentListItem.Update(); }

private static void AssignCustomListPermissionLevel(SPListItem CurrentLi stItem, SPWeb oSPWeb, SPPrincipal SPPrincipal) { //Retrieve the ID for the "Portfolio Owner - No Delete" role deffini tion to oSPRoleDefinition. SPRoleDefinition oSPRoleDefinition = oSPWeb.RoleDefinitions.GetById( 1073741933); //Add the Role Assignment for the new portfolio owner's group. SPRoleAssignment oSPRoleAssignment = new SPRoleAssignment(SPPrincipa l); //Bind the role definition to the role assignment object created for the group. oSPRoleAssignment.RoleDefinitionBindings.Add(oSPRoleDefinition); //Add it to the specified Portfolio list item. CurrentListItem.RoleAssignments.Add(oSPRoleAssignment); //update the list item. CurrentListItem.Update(); } } }

You might also like