/// <summary> /// Gets all variation labels in a site collection. This method is safe when called in console. /// </summary> /// <param name="publishingSite">Site collection.</param> /// <param name="includePending">Whether to return pending variation labels.</param> /// <returns>A read-only collection of all variation labels.</returns> public static ReadOnlyCollection <VariationLabel> GetVariationLabels(this PublishingSite publishingSite, bool includePending) { if (GetVariationLabelMethod == null) { throw new MissingMethodException("GetVariationLabel"); } List <VariationLabel> collection = new List <VariationLabel>(); publishingSite.Site.WithElevatedPrivileges(elevatedSite => { string variationsListId = (string)elevatedSite.RootWeb.AllProperties["_VarLabelsListId"]; if (!String.IsNullOrEmpty(variationsListId)) { SPList variationsList = elevatedSite.RootWeb.Lists[new Guid(variationsListId)]; CamlExpression queryExpr = Caml.IsNotNull(SPBuiltInFieldName.Title); if (!includePending) { queryExpr &= Caml.IsNotNull("Top_x0020_Web_x0020_URL"); } SPQuery query = new SPQuery { Query = queryExpr.ToString() }; foreach (SPListItem listItem in variationsList.GetItems(query)) { VariationLabel label = GetVariationLabelMethod.Invoke <VariationLabel>(null, listItem); collection.Add(label); } } }); return(collection.AsReadOnly()); }
public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPWeb web = (SPWeb)properties.Feature.Parent; SPSite site = web.Site; PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web); PublishingSite publishingSite = new PublishingSite(site); if (PublishingWeb.IsPublishingWeb(web)) { SPContentType associatedContentType = publishingSite.ContentTypes["Article Page"]; if (associatedContentType != null) { PageLayout[] pageLayouts = publishingWeb.GetAvailablePageLayouts(); PageLayout customPageLayout = GetCustomPageLayout(publishingSite, associatedContentType); List<PageLayout> newPageLayoutList = new List<PageLayout> {customPageLayout}; newPageLayoutList.AddRange(pageLayouts); if (customPageLayout != null) { publishingWeb.SetAvailablePageLayouts(newPageLayoutList.ToArray(),true); publishingWeb.SetDefaultPageLayout(pageLayouts[0],true); publishingWeb.Update(); //Mohit } } } }
private static void ProcessNewPageDefaultSettings(PublishingWeb publishingWeb, PageLayoutAndSiteTemplateSettingsDefinition definition) { var web = publishingWeb.Web; if (definition.InheritDefaultPageLayout.HasValue && definition.InheritDefaultPageLayout.Value) { publishingWeb.InheritDefaultPageLayout(); } else if (definition.UseDefinedDefaultPageLayout.HasValue && definition.UseDefinedDefaultPageLayout.Value) { var publishingSite = new PublishingSite(web.Site); var pageLayouts = publishingSite.PageLayouts; var selectedPageLayout = pageLayouts.FirstOrDefault(t => t.Name.ToUpper() == definition.DefinedDefaultPageLayout.ToUpper());; if (selectedPageLayout != null) { publishingWeb.SetDefaultPageLayout( selectedPageLayout, definition.ResetAllSubsitesToInheritDefaultPageLayout.HasValue ? definition.ResetAllSubsitesToInheritDefaultPageLayout.Value : false); } } }
/// <summary> /// Configures a page layout /// </summary> /// <param name="site">The site</param> /// <param name="pageLayoutInfo">The page layout info</param> /// <returns>The page layout</returns> public PageLayout EnsurePageLayout(SPSite site, PageLayoutInfo pageLayoutInfo) { var publishingSite = new PublishingSite(site); var pageLayout = this.GetPageLayout(publishingSite, pageLayoutInfo.Name, true); if (pageLayoutInfo.AssociatedContentTypeId != null) { var contentTypeId = site.RootWeb.ContentTypes.BestMatch(pageLayoutInfo.AssociatedContentTypeId); var ct = site.RootWeb.ContentTypes[contentTypeId]; // Applies the preview picture of the page layout // if (!string.IsNullOrEmpty(pageLayoutInfo.PreviewImagePath)) // { // pageLayout.PreviewImageUrl = SPContext.Current.Site.Url + pageLayoutInfo.PreviewImagePath; // } // Update the publishing associated content type pageLayout.AssociatedContentType = ct; pageLayout.Update(); } return(pageLayout); }
/// <summary> /// /// </summary> /// <param name="properties"></param> private void DefaultNavigation(SPWebEventProperties properties) { int level; try { using (SPSite site = new SPSite(properties.Web.Site.ID)) { using (SPWeb web = site.AllWebs[properties.WebId]) { PublishingSite pubsite = new PublishingSite(site); PublishingWeb pubWeb = this.GetPublishingSiteFromWeb(web); level = web.ServerRelativeUrl.Split('/').Length - 1; switch (level) { case 0: //Global Navigation Settings pubWeb.Navigation.GlobalIncludeSubSites = true; pubWeb.Navigation.GlobalIncludePages = false; //Current Navigation Settings pubWeb.Navigation.CurrentIncludeSubSites = true; pubWeb.Navigation.CurrentIncludePages = false; web.Update(); break; case 1: //Global Navigation Settings pubWeb.Navigation.InheritGlobal = true; pubWeb.Navigation.GlobalIncludeSubSites = true; pubWeb.Navigation.GlobalIncludePages = false; //Current Navigation Settings pubWeb.Navigation.ShowSiblings = true; pubWeb.Navigation.CurrentIncludeSubSites = true; pubWeb.Navigation.CurrentIncludePages = false; pubWeb.Update(); break; default: //Global Navigation Settings pubWeb.Navigation.InheritGlobal = true; pubWeb.Navigation.GlobalIncludeSubSites = true; pubWeb.Navigation.GlobalIncludePages = false; //Current Navigation Settings pubWeb.Navigation.InheritCurrent = true; pubWeb.Navigation.CurrentIncludeSubSites = true; pubWeb.Navigation.CurrentIncludePages = false; pubWeb.Update(); break; } } } } catch (Exception ex) { Logger.WriteLog("WebProvisioning.cs - DefaultNavigation: " + ex.Message + " " + ex.StackTrace); } }
public static void AllowPageLayouts(SPSite site, bool allow, params string[] pageLayouts) { var publishingWeb = PublishingWeb.GetPublishingWeb(site.RootWeb); if (publishingWeb != null) { if (allow) { var pageLayoutList = new ArrayList(); var pSite = publishingWeb.Web.Site; if (pSite != null) { var publishingSite = new PublishingSite(pSite); var pageLayoutsCollection = publishingSite.GetPageLayouts(true); foreach (var pl in pageLayoutsCollection) { if ( pageLayouts.ToList() .Any(p => pl.ServerRelativeUrl.ToLower().Contains(p.ToLower()))) { pageLayoutList.Add(pl); } } var newPls = (PageLayout[])pageLayoutList.ToArray(typeof(PageLayout)); publishingWeb.SetAvailablePageLayouts(newPls, false); publishingWeb.Update(); } } else { var availablePageLayouts = publishingWeb.GetAvailablePageLayouts(); var pageLayoutList = new ArrayList(); pageLayoutList.AddRange(availablePageLayouts); var pSite = publishingWeb.Web.Site; if (pSite != null) { var publishingSite = new PublishingSite(pSite); var pageLayoutsCollection = publishingSite.GetPageLayouts(true); foreach (PageLayout pl in pageLayoutsCollection) { if ( pageLayouts.ToList() .Any(p => pl.ServerRelativeUrl.ToLower().Contains(p.ToLower()))) { if (pageLayoutList.Contains(pl)) { pageLayoutList.Remove(pl); } } } var newPls = (PageLayout[])pageLayoutList.ToArray(typeof(PageLayout)); publishingWeb.SetAvailablePageLayouts(newPls, false); publishingWeb.Update(); } } } }
private void PollPublishingWebActivated(string webUrl, int delay = 0) { bool poll = false; SPSecurity.RunWithElevatedPrivileges(delegate() { //TraceLogger.TraceInfo("Checking for PublishingWeb at '{0}' (attempt {1})", webUrl, attempt); using (SPSite site = new SPSite(webUrl)) using (SPWeb newWeb = site.OpenWeb()) { if (PublishingWeb.IsPublishingWeb(newWeb)) { PublishingSite pubSite = new PublishingSite(site); var pubWeb = PublishingWeb.GetPublishingWeb(newWeb); SPList pages = null; try { pages = pubWeb.PagesList; } catch { } if (pages != null) { pages.EnableModeration = false; pages.EnableVersioning = true; pages.EnableMinorVersions = false; pages.MajorVersionLimit = 5; pages.ForceCheckout = false; pages.Update(); } if (OnPublishingWebActivated != null) { OnPublishingWebActivated(newWeb, pubSite, pubWeb); } if (OnPublishingActivated != null) { OnPublishingActivated(webUrl); } } else { //TraceLogger.TraceInfo("Web at '{0}' IS NOT a publishing Web (yet)!", webUrl); poll = delay < PUBLISHING_MAX_DELAY; } } }); if (poll) { Timer timer = new System.Timers.Timer(POLL_SPEED); timer.AutoReset = false; timer.Elapsed += delegate { PollPublishingWebActivated(webUrl, delay += POLL_SPEED); }; timer.Enabled = true; } }
void activation_OnPublishingWebActivated(SPWeb web, PublishingSite pubSite, PublishingWeb pubWeb) { // do stuff requiring publishing feature activation here pubWeb.Navigation.InheritGlobal = true; pubWeb.Navigation.GlobalIncludePages = false; pubWeb.Navigation.GlobalIncludeSubSites = true; SPFile homePageFile = web.GetFile("default.aspx"); pubWeb.DefaultPage = homePageFile; pubWeb.Update(); }
private PublishingWeb GetPublishingSiteFromWeb(SPWeb web) { PublishingWeb result = null; if (web == null) { throw new ArgumentNullException("web"); } var pubSite = new PublishingSite(web.Site); if (PublishingWeb.IsPublishingWeb(web)) { result = PublishingWeb.GetPublishingWeb(web); } return(result); }
/// <summary> /// Creates a publishing page under the specified site with the content type ID and specified title. /// Filename of the created page is automatically chosen to avoid collision to existing pages. /// </summary> /// <param name="currentWeb">Publishing web.</param> /// <param name="contentTypeId">Content type ID of the new page.</param> /// <param name="title">Title of the new page.</param> /// <exception cref="InvalidOperationException">Throws if there is no page layouts associated with the specified content type ID.</exception> /// <returns>A publishing page object.</returns> public static PublishingPage CreatePublishingPage(this PublishingWeb currentWeb, SPContentTypeId contentTypeId, string title) { CommonHelper.ConfirmNotNull(currentWeb, "currentWeb"); CommonHelper.ConfirmNotNull(title, "title"); PageLayout pageLayout = null; currentWeb.Web.Site.WithElevatedPrivileges(elevatedSite => { PublishingSite publishingSite = new PublishingSite(elevatedSite); IEnumerable <PageLayout> pageLayouts = publishingSite.GetPageLayouts(true).Where(p => p.AssociatedContentType != null); pageLayout = pageLayouts.FirstOrDefault(p => p.AssociatedContentType.Id == contentTypeId); if (pageLayout == null) { pageLayout = pageLayouts.FirstOrDefault(p => p.AssociatedContentType.Id.IsChildOf(contentTypeId)); } //pageLayout = publishingWeb.GetAvailablePageLayouts().FirstOrDefault(p => p.AssociatedContentType.Id == contentTypeId); //pageLayout = publishingWeb.GetAvailablePageLayouts(contentTypeId).FirstOrDefault(); }); if (pageLayout == null) { throw new InvalidOperationException(String.Format("Could not find available page layout for content type {0} at {1}", contentTypeId, currentWeb.Url)); } MethodInfo getUniquePageName = typeof(PublishingPage).GetMethod("GetUniquePageName", true, typeof(string), typeof(bool), typeof(PublishingWeb), typeof(bool)) ?? typeof(PublishingPage).GetMethod("GetUniquePageName", true, typeof(string), typeof(bool), typeof(PublishingWeb)); if (getUniquePageName == null) { throw new MissingMethodException("PublishingPage", "GetUniquePageName"); } object[] param = getUniquePageName.GetParameters().Length == 4 ? new object[] { title, true, currentWeb, true } : new object[] { title, true, currentWeb }; string uniquePageName = getUniquePageName.Invoke <string>(null, param); PublishingPage publishingPage = currentWeb.AddPublishingPage(uniquePageName, pageLayout); publishingPage.Title = title; publishingPage.Update(); return(publishingPage); }
/// <summary> /// Creates a page in the Pages library /// </summary> /// <param name="currentWeb">The current web</param> /// <param name="folderId">The folder in which to add the item</param> /// <param name="contentTypeId">Id of Content Type to create</param> /// <param name="pageLayoutName">Name (filename) of Page Layout to apply</param> /// <param name="pageTitle">The human-readable title of the page</param> /// <param name="pageName">The url/name of the page relative to its parent folder</param> /// <returns>The newly created publishing page</returns> public PublishingPage Create(SPWeb currentWeb, int folderId, SPContentTypeId contentTypeId, string pageLayoutName, string pageTitle, string pageName) { PublishingPage newPage = null; var folder = this._folderRepository.GetFolderByIdForWeb(currentWeb, folderId); if (folder.Item.DoesUserHavePermissions(SPBasePermissions.AddListItems)) { using (new Unsafe(currentWeb)) { SPContentType pubPageBaseContentType = currentWeb.AvailableContentTypes[ContentTypeId.ArticlePage]; var requestedContentType = currentWeb.AvailableContentTypes[contentTypeId]; if (null != requestedContentType && requestedContentType.Id.IsChildOf(pubPageBaseContentType.Id)) { var publishingSite = new PublishingSite(currentWeb.Site); PageLayoutCollection pageLayoutsForCT = publishingSite.GetPageLayouts(requestedContentType, false); var requestedPageLayout = pageLayoutsForCT.Cast<PageLayout>().FirstOrDefault(layout => layout.Name == pageLayoutName); if (requestedPageLayout != null) { PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(currentWeb); if (!pageName.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)) { pageName += ".aspx"; } newPage = publishingWeb.GetPublishingPages().Add(folder.ServerRelativeUrl + "/" + pageName, requestedPageLayout); newPage.ListItem[BuiltInFields.Title.InternalName] = pageTitle; newPage.ListItem[BuiltInFields.ContentType.InternalName] = requestedContentType.Name; newPage.ListItem[BuiltInFields.ContentTypeId.InternalName] = requestedContentType.Id; newPage.ListItem.Update(); } } } } return newPage; }
/// <summary> /// Create publishing page in Pages Library /// </summary> /// <param name="web">the current web</param> /// <param name="folderId">the current folder id</param> /// <param name="contentTypeId">the current content type id</param> /// <param name="pageLayoutName">the page layout name</param> /// <param name="pageTitle">the page title</param> /// <param name="pageName">the page name</param> /// <returns>the created publishing page</returns> public PublishingPage Create(SPWeb web, int folderId, SPContentTypeId contentTypeId, string pageLayoutName, string pageTitle, string pageName) { var publishingSite = new PublishingSite(web.Site); var pageLayout = this.GetPageLayout(publishingSite, pageLayoutName, false); var page = new PageInfo() { Name = pageName, ContentTypeId = contentTypeId, PageLayout = pageLayout, Values = new List<IFieldValueInfo>() { new FieldValueInfo() { FieldName = BuiltInFields.Title.InternalName, Value = pageTitle } } }; return this.Create(web, folderId, page); }
private static void ProcessPageLayoutSettings(PublishingWeb publishingWeb, PageLayoutAndSiteTemplateSettingsDefinition definition) { var web = publishingWeb.Web; if (definition.InheritPageLayouts.HasValue && definition.InheritPageLayouts.Value) { publishingWeb.InheritAvailablePageLayouts(); } else if (definition.UseAnyPageLayout.HasValue && definition.UseAnyPageLayout.Value) { publishingWeb.AllowAllPageLayouts(definition.ResetAllSubsitesToInheritPageLayouts.HasValue ? definition.ResetAllSubsitesToInheritPageLayouts.Value : false); } else if (definition.UseDefinedPageLayouts.HasValue && definition.UseDefinedPageLayouts.Value) { var publishingSite = new PublishingSite(web.Site); var pageLayouts = publishingSite.PageLayouts; var selectedPageLayouts = new List <PageLayout>(); foreach (var selectedLayoutName in definition.DefinedPageLayouts) { var targetLayout = pageLayouts.FirstOrDefault(t => t.Name.ToUpper() == selectedLayoutName.ToUpper()); if (targetLayout != null) { selectedPageLayouts.Add(targetLayout); } } if (selectedPageLayouts.Any()) { publishingWeb.SetAvailablePageLayouts(selectedPageLayouts.ToArray(), definition.ResetAllSubsitesToInheritPageLayouts.HasValue ? definition.ResetAllSubsitesToInheritPageLayouts.Value : false); } } }
// Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSite site = (SPSite)properties.Feature.Parent; if (PublishingSite.IsPublishingSite(site)) { PublishingSite pubSite = new PublishingSite(site); Uri layoutURI = new Uri(site.RootWeb.Url + "_catalogs/masterpage/AccueilLayout.aspx"); PageLayout layout = pubSite.PageLayouts[layoutURI.ToString()]; updateLayout(layout); layoutURI = new Uri(site.RootWeb.Url + "_catalogs/masterpage/XAPLayout.aspx"); layout = pubSite.PageLayouts[layoutURI.ToString()]; updateLayout(layout); layoutURI = new Uri(site.RootWeb.Url + "_catalogs/masterpage/SearchLayout.aspx"); layout = pubSite.PageLayouts[layoutURI.ToString()]; updateLayout(layout); } }
private static void ProcessNewPageDefaultSettings(PublishingWeb publishingWeb, PageLayoutAndSiteTemplateSettingsDefinition definition) { var web = publishingWeb.Web; if (definition.InheritDefaultPageLayout.HasValue && definition.InheritDefaultPageLayout.Value) publishingWeb.InheritDefaultPageLayout(); else if (definition.UseDefinedDefaultPageLayout.HasValue && definition.UseDefinedDefaultPageLayout.Value) { var publishingSite = new PublishingSite(web.Site); var pageLayouts = publishingSite.PageLayouts; var selectedPageLayout = pageLayouts.FirstOrDefault(t => t.Name.ToUpper() == definition.DefinedDefaultPageLayout.ToUpper()); ; if (selectedPageLayout != null) { publishingWeb.SetDefaultPageLayout( selectedPageLayout, definition.ResetAllSubsitesToInheritDefaultPageLayout.HasValue ? definition.ResetAllSubsitesToInheritDefaultPageLayout.Value : false); } } }
/// <summary> /// Configures a page layout /// </summary> /// <param name="site">The site</param> /// <param name="pageLayoutInfo">The page layout info</param> /// <returns>The page layout</returns> public PageLayout EnsurePageLayout(SPSite site, PageLayoutInfo pageLayoutInfo) { var publishingSite = new PublishingSite(site); var pageLayout = this.GetPageLayout(publishingSite, pageLayoutInfo.Name, true); if (pageLayoutInfo.AssociatedContentTypeId != null) { var contentTypeId = site.RootWeb.ContentTypes.BestMatch(pageLayoutInfo.AssociatedContentTypeId); var ct = site.RootWeb.ContentTypes[contentTypeId]; // Applies the preview picture of the page layout if (pageLayoutInfo.PreviewImageUrl != null) { Uri previewImageUrl; if (!pageLayoutInfo.PreviewImageUrl.IsAbsoluteUri) { previewImageUrl = new Uri(new Uri(site.Url), pageLayoutInfo.PreviewImageUrl); } else { previewImageUrl = pageLayoutInfo.PreviewImageUrl; } pageLayout.PreviewImageUrl = previewImageUrl.AbsoluteUri; } // Update the publishing associated content type pageLayout.AssociatedContentType = ct; pageLayout.Update(); pageLayout.ListItem.File.Publish("Dynamite Ensure Major Version"); } return(pageLayout); }
private static void ProcessPageLayoutSettings(PublishingWeb publishingWeb, PageLayoutAndSiteTemplateSettingsDefinition definition) { var web = publishingWeb.Web; if (definition.InheritPageLayouts.HasValue && definition.InheritPageLayouts.Value) publishingWeb.InheritAvailablePageLayouts(); else if (definition.UseAnyPageLayout.HasValue && definition.UseAnyPageLayout.Value) { publishingWeb.AllowAllPageLayouts(definition.ResetAllSubsitesToInheritPageLayouts.HasValue ? definition.ResetAllSubsitesToInheritPageLayouts.Value : false); } else if (definition.UseDefinedPageLayouts.HasValue && definition.UseDefinedPageLayouts.Value) { var publishingSite = new PublishingSite(web.Site); var pageLayouts = publishingSite.PageLayouts; var selectedPageLayouts = new List<PageLayout>(); foreach (var selectedLayoutName in definition.DefinedPageLayouts) { var targetLayout = pageLayouts.FirstOrDefault(t => t.Name.ToUpper() == selectedLayoutName.ToUpper()); if (targetLayout != null) selectedPageLayouts.Add(targetLayout); } if (selectedPageLayouts.Any()) { publishingWeb.SetAvailablePageLayouts(selectedPageLayouts.ToArray(), definition.ResetAllSubsitesToInheritPageLayouts.HasValue ? definition.ResetAllSubsitesToInheritPageLayouts.Value : false); } } }
/// <summary> /// Method that take a list of PageLayoutInfo and Set them as the Available Page Layout. /// </summary> /// <param name="site">The Site Collection to Set the available Page Layout</param> /// <param name="pageLayoutInfos">The List of Page Layout Info to set as default</param> public void SetAvailablePageLayouts(SPSite site, IList <PageLayoutInfo> pageLayoutInfos) { var publishingSite = new PublishingSite(site); var availablePageLayouts = new List <PageLayout>(); var allPageLayouts = publishingSite.GetPageLayouts(false).Cast <PageLayout>(); // Build the Available Page Layout list foreach (var pageLayout in allPageLayouts) { if (pageLayoutInfos.Any(x => x.Name == pageLayout.Name)) { availablePageLayouts.Add(pageLayout); } } // Set The Available Page Layouts for each Webs of the Site foreach (SPWeb web in site.AllWebs) { var publishingWeb = PublishingWeb.GetPublishingWeb(web); publishingWeb.SetAvailablePageLayouts(availablePageLayouts.ToArray(), true); publishingWeb.Update(); } }
/// <summary> /// Ensure a publishing page in a folder /// </summary> /// <param name="library">The library</param> /// <param name="folder">The folder</param> /// <param name="page">The page information</param> /// <returns>The publishing page object</returns> public PublishingPage EnsurePage(SPList library, SPFolder folder, PageInfo page) { var publishingSite = new PublishingSite(library.ParentWeb.Site); if (!PublishingWeb.IsPublishingWeb(library.ParentWeb)) { throw new ArgumentException("Publishing pages cannot be provisionned outside of a Publishing web (choose the Publishing Site or Enterprise Wiki site definition)."); } var publishingWeb = PublishingWeb.GetPublishingWeb(library.ParentWeb); var recursivePagesQuery = new SPQuery() { ViewAttributes = "Scope=\"Recursive\"" }; var publishingPages = publishingWeb.GetPublishingPages(recursivePagesQuery); PageLayout pageLayout = null; // Get the correct Page Layout according to its name (<xxx>.aspx) var pageLayoutInfo = this.GetPageLayout(publishingSite, page.PageLayout.Name, true); // If a page layout was specified and its from the correct web. if (pageLayoutInfo != null && pageLayoutInfo.ListItem.ParentList.ParentWeb.ID == publishingSite.RootWeb.ID) { // Associate the page layout specified in the page. pageLayout = pageLayoutInfo; } var pageServerRelativeUrl = folder.ServerRelativeUrl + "/" + page.FileName + ".aspx"; Uri baseUri = new Uri(library.ParentWeb.Url, UriKind.Absolute); var publishingPage = publishingPages.ToList().Find( x => Uri.Compare(x.Uri, new Uri(baseUri, pageServerRelativeUrl), UriComponents.AbsoluteUri, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0); if (publishingPage == null) { // Only create the page if it doesn't exist yet and allow event firing on ItemAdded publishingPage = publishingPages.Add(pageServerRelativeUrl, pageLayout); } else { this.EnsurePageCheckOut(publishingPage); // Update the Page layout. publishingPage.Layout = pageLayout; publishingPage.Update(); } // Set the title if (!string.IsNullOrEmpty(page.Title)) { publishingPage.Title = page.Title; publishingPage.Update(); } // Set field Values this.itemValueWriter.WriteValuesToListItem(publishingPage.ListItem, page.FieldValues); publishingPage.ListItem.Update(); // Insert WebParts foreach (WebPartInfo webPartSetting in page.WebParts) { this.webPartHelper.EnsureWebPart(publishingPage.ListItem, webPartSetting); } // Publish PageHelper.EnsurePageCheckInAndPublish(page, publishingPage); return publishingPage; }
public static PublishingPage CreatePage(SPWeb web, string pageName, string title, string layoutName, Dictionary <string, string> fieldDataCollection, bool test) { if (!PublishingWeb.IsPublishingWeb(web)) { throw new ArgumentException("The specified web is not a publishing web."); } PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web); PageLayout layout = null; string availableLayouts = string.Empty; foreach (PageLayout lo in pubweb.GetAvailablePageLayouts()) { availableLayouts += "\t" + lo.Name + "\r\n"; if (lo.Name.ToLowerInvariant() == layoutName.ToLowerInvariant()) { layout = lo; break; } } if (layout == null) { if (PublishingSite.IsPublishingSite(web.Site)) { Logger.WriteWarning("The specified page layout could not be found among the list of available page layouts for the web. Available layouts are:\r\n" + availableLayouts); availableLayouts = string.Empty; foreach (PageLayout lo in (new PublishingSite(web.Site).PageLayouts)) { availableLayouts += "\t" + lo.Name + "\r\n"; if (lo.Name.ToLowerInvariant() == layoutName.ToLowerInvariant()) { layout = lo; break; } } } if (layout == null) { throw new ArgumentException("The layout specified could not be found. Available layouts are:\r\n" + availableLayouts); } } if (!pageName.ToLowerInvariant().EndsWith(".aspx")) { pageName += ".aspx"; } PublishingPage page = null; SPListItem item = null; if (test) { Logger.Write("Page to be created at {0}", pubweb.Url); } else { page = pubweb.GetPublishingPages().Add(pageName, layout); page.Title = title; item = page.ListItem; } foreach (string fieldName in fieldDataCollection.Keys) { string fieldData = fieldDataCollection[fieldName]; try { SPField field = item.Fields.GetFieldByInternalName(fieldName); if (field.ReadOnlyField) { Logger.Write("Field '{0}' is read only and will not be updated.", field.InternalName); continue; } if (field.Type == SPFieldType.Computed) { Logger.Write("Field '{0}' is a computed column and will not be updated.", field.InternalName); continue; } if (!test) { if (field.Type == SPFieldType.URL) { item[field.Id] = new SPFieldUrlValue(fieldData); } else if (field.Type == SPFieldType.User) { Common.Pages.CreatePublishingPage.SetUserField(web, item, field, fieldData); } else { item[field.Id] = fieldData; } } else { Logger.Write("Field '{0}' would be set to '{1}'.", field.InternalName, fieldData); } } catch (ArgumentException ex) { Logger.WriteException(new ErrorRecord(new Exception(string.Format("Could not set field {0} for item {1}.", fieldName, item.ID), ex), null, ErrorCategory.InvalidArgument, item)); } } if (page != null) { page.Update(); } return(page); }
/// <summary> /// Get the page layout /// </summary> /// <param name="publishingSite">the current publishing site</param> /// <param name="pageLayoutName">the page layout name</param> /// <param name="excludeObsolete">exclude obsolete page layout</param> /// <returns>the page layout</returns> public PageLayout GetPageLayout(PublishingSite publishingSite, string pageLayoutName, bool excludeObsolete) { return(publishingSite.GetPageLayouts(excludeObsolete).Cast <PageLayout>().FirstOrDefault(pageLayout => pageLayout.Name == pageLayoutName)); }
// Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSite currentSite = (SPSite)properties.Feature.Parent; if (PublishingSite.IsPublishingSite(currentSite)) { PublishingSite pubSite = new PublishingSite(currentSite); SPWeb currentWeb = currentSite.RootWeb; SPFile myStyle = currentWeb.GetFile("Style Library/proteca.css"); if (myStyle != null && myStyle.Exists) { if (myStyle.CheckedOutByUser != null) { myStyle.UndoCheckOut(); myStyle.Update(); } myStyle.CheckOut(); myStyle.Update(); myStyle.CheckIn("Automatically checked in by PROTECAMasterPage feature", SPCheckinType.MajorCheckIn); myStyle.Update(); } Uri masterURI = new Uri(currentWeb.Url + "/_catalogs/masterpage/PROTECA.master"); SPFile masterFile = currentWeb.GetFile("/_catalogs/masterpage/PROTECA.master"); if (masterFile != null && masterFile.Exists) { if (masterFile.CheckedOutByUser != null) { masterFile.UndoCheckOut(); masterFile.Update(); } masterFile.CheckOut(); masterFile.Update(); masterFile.CheckIn("Automatically checked in by PROTECAMasterPage feature", SPCheckinType.MajorCheckIn); masterFile.Update(); } currentWeb.AllowUnsafeUpdates = true; //currentWeb.MasterUrl = masterURI.AbsolutePath; currentWeb.CustomMasterUrl = masterURI.AbsolutePath; currentWeb.Update(); currentWeb.AllowUnsafeUpdates = false; foreach (SPWeb subWeb in currentSite.AllWebs) { if (subWeb.IsRootWeb) continue; subWeb.AllowUnsafeUpdates = true; Hashtable hash = subWeb.AllProperties; subWeb.MasterUrl = subWeb.ParentWeb.MasterUrl; hash["__InheritsMasterUrl"] = "True"; subWeb.CustomMasterUrl = subWeb.ParentWeb.CustomMasterUrl; hash["__InheritsCustomMasterUrl"] = "True"; subWeb.Update(); subWeb.AllowUnsafeUpdates = false; } } }
public void EnsureFolderHierarchy_WhenPagesAlreadyEnsured_AndPageInfoIsRenamed_ShouldNotDeleteExistingPage_AndCreateABrandNewPage() { using (var testScope = SiteTestScope.PublishingSite()) { // Arrange var articleLeftPageLayout = new PageLayoutInfo("ArticleLeft.aspx", new SPContentTypeId("0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D")); var welcomePageLayout = new PageLayoutInfo("WelcomeSplash.aspx", new SPContentTypeId("0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390064DEA0F50FC8C147B0B6EA0636C4A7D4")); var level1PageInfo = new PageInfo("Hello-root-page-path", welcomePageLayout) { FieldValues = new List<FieldValueInfo>() { new FieldValueInfo(PublishingFields.PublishingPageContent, "<div><p>My HTML rocks!!!</p></div>") } }; var level2PageInfo = new PageInfo("Hello-lvl-2-page-path", articleLeftPageLayout) { FieldValues = new List<FieldValueInfo>() { new FieldValueInfo(PublishingFields.PublishingPageContent, "<div><p>Hi LVL 2!!! My HTML rocks!!!</p></div>") } }; var rootFolderInfo = new FolderInfo("somepath") { Subfolders = new List<FolderInfo>() { new FolderInfo("somelevel2path") { Pages = new List<PageInfo>() { level2PageInfo } } }, Pages = new List<PageInfo>() { level1PageInfo } }; using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { var folderHelper = injectionScope.Resolve<IFolderHelper>(); var pagesLibrary = testScope.SiteCollection.RootWeb.GetPagesLibrary(); // Ensure the hierarchy a first time with the initial page values folderHelper.EnsureFolderHierarchy(pagesLibrary, rootFolderInfo); // Edit the PageInfos slightly level1PageInfo.FileName = "Hello-welcome-page-renamed"; level2PageInfo.FileName = "Hello-level-2-page-renamed"; // Act: re-ensure the same hierarchy folderHelper.EnsureFolderHierarchy(pagesLibrary, rootFolderInfo); // Assert: new pages should've been created and the old ones should still be there var publishingSite = new PublishingSite(pagesLibrary.ParentWeb.Site); var publishingWeb = PublishingWeb.GetPublishingWeb(pagesLibrary.ParentWeb); var recursivePagesQuery = new SPQuery() { ViewAttributes = "Scope=\"Recursive\"" }; var publishingPages = publishingWeb.GetPublishingPages(recursivePagesQuery); Assert.AreEqual(4, publishingPages.Cast<PublishingPage>().Where(p => p.Name.StartsWith("Hello")).Count()); var ensuredWelcomePage = publishingPages.Cast<PublishingPage>().Single(p => p.Name.StartsWith("Hello-root-page-path")); var ensuredLevel2Page = publishingPages.Cast<PublishingPage>().Single(p => p.Name.StartsWith("Hello-lvl-2-page-path")); var extraEnsuredWelcomePage = publishingPages.Cast<PublishingPage>().Single(p => p.Name.StartsWith("Hello-welcome-page-renamed")); var extraEnsuredLevel2Page = publishingPages.Cast<PublishingPage>().Single(p => p.Name.StartsWith("Hello-level-2-page-renamed")); } } }
/// <summary> /// Method that will return custom added page layout /// </summary> /// <param name="publishingSite"></param> /// <param name="contentType"></param> /// <returns>PageLayout</returns> private static PageLayout GetCustomPageLayout(PublishingSite publishingSite, SPContentType contentType) { PageLayoutCollection pageLayouts = publishingSite.GetPageLayouts(contentType, true); return pageLayouts.FirstOrDefault(pageLayout => string.Equals(pageLayout.Name, "PageFromDocLayoutWithLeftMenu.aspx")); }
/// <summary> /// Configures a page layout /// </summary> /// <param name="site">The site</param> /// <param name="pageLayoutInfo">The page layout info</param> /// <returns>The page layout</returns> public PageLayout EnsurePageLayout(SPSite site, PageLayoutInfo pageLayoutInfo) { var publishingSite = new PublishingSite(site); var pageLayout = this.GetPageLayout(publishingSite, pageLayoutInfo.Name, true); if (pageLayoutInfo.AssociatedContentTypeId != null) { var contentTypeId = site.RootWeb.ContentTypes.BestMatch(pageLayoutInfo.AssociatedContentTypeId); var ct = site.RootWeb.ContentTypes[contentTypeId]; // Applies the preview picture of the page layout // if (!string.IsNullOrEmpty(pageLayoutInfo.PreviewImagePath)) // { // pageLayout.PreviewImageUrl = SPContext.Current.Site.Url + pageLayoutInfo.PreviewImagePath; // } // Update the publishing associated content type pageLayout.AssociatedContentType = ct; pageLayout.Update(); } return pageLayout; }
public void CreatePage(SPWeb web) { PublishingSite pubSiteCollection = new PublishingSite(web.Site); PublishingWeb pubSite = null; if (pubSiteCollection != null) { // Assign an object to the pubSite variable if (PublishingWeb.IsPublishingWeb(web)) { pubSite = PublishingWeb.GetPublishingWeb(web); } } // Search for the page layout for creating the new page PageLayout currentPageLayout = FindPageLayout(pubSiteCollection, Layout); // Check or the Page Layout could be found in the collection // if not (== null, return because the page has to be based on // an excisting Page Layout if (currentPageLayout == null) { return; } PublishingPageCollection pages = pubSite.GetPublishingPages(); PublishingPage newPage = pages.Add(FileName, currentPageLayout); newPage.Title = Title; //newPage.Description = ComponentDescription; // Here you can set some properties like: newPage.IncludeInCurrentNavigation = true; newPage.IncludeInGlobalNavigation = true; // End of setting properties var item = newPage.ListItem; if (PageTags != null && PageTags.Any()) { item["Tags"] = string.Join(";#", PageTags); } if (FileContent.ContainsKey("Content")) { item["PublishingPageContent"] = FileContent["Content"]; } item.Update(); newPage.Update(); foreach (var wpd in WebParts) { wpd.AddToPage(web, item.File.Url, true); } if (IsWelcomePage) { pubSite.DefaultPage = item.File; pubSite.Update(); } /* // Check the file in (a major version) publishFile.CheckIn("Initial", SPCheckinType.MajorCheckIn); publishFile.Publish("Initial"); // In case of content approval, approve the file if (pubSite.PagesList.EnableModeration) { publishFile.Approve("Initial"); } */ }
private PageLayout FindPageLayout(PublishingSite pubSiteCollection, string templateName) { PageLayoutCollection plCollection = pubSiteCollection.GetPageLayouts(true); foreach (Microsoft.SharePoint.Publishing.PageLayout layout in plCollection) { // String Comparison based on the Page Layout Name if (layout.Name.Equals(templateName, StringComparison.InvariantCultureIgnoreCase)) { return layout; } } return null; }
public void EnsureFolderHierarchy_WhenInPagesLibrary_AndNotEnsuredYet_ShouldCreatePublishingPages() { using (var testScope = SiteTestScope.PublishingSite()) { // Arrange var articleLeftPageLayout = new PageLayoutInfo("ArticleLeft.aspx", new SPContentTypeId("0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D")); var welcomePageLayout = new PageLayoutInfo("WelcomeSplash.aspx", new SPContentTypeId("0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390064DEA0F50FC8C147B0B6EA0636C4A7D4")); var rootFolderInfo = new FolderInfo("somepath") { Subfolders = new List<FolderInfo>() { new FolderInfo("somelevel2path") { Subfolders = new List<FolderInfo>() { new FolderInfo("level3") { Pages = new List<PageInfo>() { new PageInfo("Hello-lvl-3-page-path", articleLeftPageLayout) { FieldValues = new List<FieldValueInfo>() { new FieldValueInfo(PublishingFields.PublishingPageContent, "<div><p>Hi LVL 3!!! My HTML rocks!!!</p></div>") } }, new PageInfo("Hello-lvl-3-page-path-bis", articleLeftPageLayout) { FieldValues = new List<FieldValueInfo>() { new FieldValueInfo(PublishingFields.PublishingPageContent, "<div><p>Hi LVL 3 AGAIN!!! My HTML rocks!!!</p></div>") } }, } } }, Pages = new List<PageInfo>() { new PageInfo("Hello-lvl-2-page-path", articleLeftPageLayout) { FieldValues = new List<FieldValueInfo>() { new FieldValueInfo(PublishingFields.PublishingPageContent, "<div><p>Hi LVL 2!!! My HTML rocks!!!</p></div>") } } } } }, Pages = new List<PageInfo>() { new PageInfo("Hello-root-page-path", welcomePageLayout) { FieldValues = new List<FieldValueInfo>() { new FieldValueInfo(PublishingFields.PublishingPageContent, "<div><p>My HTML rocks!!!</p></div>") } } } }; using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { var folderHelper = injectionScope.Resolve<IFolderHelper>(); var pagesLibrary = testScope.SiteCollection.RootWeb.GetPagesLibrary(); // Act folderHelper.EnsureFolderHierarchy(pagesLibrary, rootFolderInfo); // Assert var publishingSite = new PublishingSite(pagesLibrary.ParentWeb.Site); var publishingWeb = PublishingWeb.GetPublishingWeb(pagesLibrary.ParentWeb); var recursivePagesQuery = new SPQuery() { ViewAttributes = "Scope=\"Recursive\"" }; var publishingPages = publishingWeb.GetPublishingPages(recursivePagesQuery); Assert.AreEqual(4, publishingPages.Cast<PublishingPage>().Where(p => p.Name.StartsWith("Hello")).Count()); var ensuredWelcomePage = publishingPages.Cast<PublishingPage>().Single(p => p.Name.StartsWith("Hello-root-page-path")); Assert.IsTrue(ensuredWelcomePage.ContentType.Id.IsChildOf(welcomePageLayout.AssociatedContentTypeId)); var ensuredLevel2Page = publishingPages.Cast<PublishingPage>().Single(p => p.Name.StartsWith("Hello-lvl-2-page-path")); Assert.IsTrue(ensuredLevel2Page.ContentType.Id.IsChildOf(articleLeftPageLayout.AssociatedContentTypeId)); Assert.AreEqual("<div><p>Hi LVL 2!!! My HTML rocks!!!</p></div>", ensuredLevel2Page.ListItem[PublishingFields.PublishingPageContent.Id].ToString()); } } }
/// <summary> /// Ensure a publishing page in a folder /// </summary> /// <param name="library">The library</param> /// <param name="folder">The folder</param> /// <param name="page">The page information</param> /// <returns>The publishing page object</returns> public PublishingPage EnsurePage(SPList library, SPFolder folder, PageInfo page) { var publishingSite = new PublishingSite(library.ParentWeb.Site); if (!PublishingWeb.IsPublishingWeb(library.ParentWeb)) { throw new ArgumentException("Publishing pages cannot be provisionned outside of a Publishing web (choose the Publishing Site or Enterprise Wiki site definition)."); } var publishingWeb = PublishingWeb.GetPublishingWeb(library.ParentWeb); var recursivePagesQuery = new SPQuery() { ViewAttributes = "Scope=\"Recursive\"" }; var publishingPages = publishingWeb.GetPublishingPages(recursivePagesQuery); PageLayout pageLayout = null; // Get the correct Page Layout according to its name (<xxx>.aspx) var pageLayoutInfo = this.GetPageLayout(publishingSite, page.PageLayout.Name, true); // If a page layout was specified and its from the correct web. if (pageLayoutInfo != null && pageLayoutInfo.ListItem.ParentList.ParentWeb.ID == publishingSite.RootWeb.ID) { // Associate the page layout specified in the page. pageLayout = pageLayoutInfo; } var pageServerRelativeUrl = folder.ServerRelativeUrl + "/" + page.FileName + ".aspx"; Uri baseUri = new Uri(library.ParentWeb.Url, UriKind.Absolute); var publishingPage = publishingPages.ToList().Find( x => Uri.Compare(x.Uri, new Uri(baseUri, pageServerRelativeUrl), UriComponents.AbsoluteUri, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0); if (publishingPage == null) { // Only create the page if it doesn't exist yet and allow event firing on ItemAdded publishingPage = publishingPages.Add(pageServerRelativeUrl, pageLayout); } else { this.EnsurePageCheckOut(publishingPage); // Update the Page layout. publishingPage.Layout = pageLayout; publishingPage.Update(); } // Set the title if (!string.IsNullOrEmpty(page.Title)) { publishingPage.Title = page.Title; publishingPage.Update(); } // Set field Values this.itemValueWriter.WriteValuesToListItem(publishingPage.ListItem, page.FieldValues); publishingPage.ListItem.Update(); // Insert WebParts foreach (WebPartInfo webPartSetting in page.WebParts) { this.webPartHelper.EnsureWebPart(publishingPage.ListItem, webPartSetting); } // Publish PageHelper.EnsurePageCheckInAndPublish(page, publishingPage); return(publishingPage); }
/// <summary> /// Method that take a list of PageLayoutInfo and Set them as the Available Page Layout. /// </summary> /// <param name="site">The Site Collection to Set the available Page Layout</param> /// <param name="pageLayoutInfos">The List of Page Layout Info to set as default</param> public void SetAvailablePageLayouts(SPSite site, IList<PageLayoutInfo> pageLayoutInfos) { var publishingSite = new PublishingSite(site); var availablePageLayouts = new List<PageLayout>(); var allPageLayouts = publishingSite.GetPageLayouts(false).Cast<PageLayout>(); // Build the Available Page Layout list foreach (var pageLayout in allPageLayouts) { if (pageLayoutInfos.Any(x => x.Name == pageLayout.Name)) { availablePageLayouts.Add(pageLayout); } } // Set The Available Page Layouts for each Webs of the Site foreach (SPWeb web in site.AllWebs) { var publishingWeb = PublishingWeb.GetPublishingWeb(web); publishingWeb.SetAvailablePageLayouts(availablePageLayouts.ToArray(), true); publishingWeb.Update(); } }
private void AddFolderPages(SPList library, SPFolder folder, IFolderInfo folderInfo) { if (folderInfo.Pages != null) { var publishingSite = new PublishingSite(library.ParentWeb.Site); var publishingWeb = PublishingWeb.GetPublishingWeb(library.ParentWeb); var publishingPages = publishingWeb.GetPublishingPages(); foreach (var page in folderInfo.Pages) { PageLayout pageLayout; // If a page layout was specified and its from the correct web. if (page.PageLayout != null && page.PageLayout.ListItem.ParentList.ParentWeb.ID == publishingSite.RootWeb.ID) { // Associate the page layout specified in the page. pageLayout = page.PageLayout; } else { // Get the first page layout with the specified content type id. var pageContentType = publishingSite.ContentTypes[page.ContentTypeId]; var pageLayouts = publishingSite.GetPageLayouts(pageContentType, true); pageLayout = pageLayouts[0]; // default to first associated page layout } var pageServerRelativeUrl = folder.ServerRelativeUrl + "/" + page.Name + ".aspx"; var existingPage = publishingWeb.GetPublishingPage(pageServerRelativeUrl); if (existingPage == null) { // Only create the page if it doesn't exist yet var publishingPage = publishingPages.Add(pageServerRelativeUrl, pageLayout); this.EnsurePageCheckOut(publishingPage); var item = publishingPage.ListItem; ApplyPageValues(item, page); publishingPage.Update(); // Add webparts to the page this.EnsureWebpartsOnPage(publishingPage); if (page.IsWelcomePage) { folder.WelcomePage = item.Name; folder.Update(); EnsureFolderPublish(folder); if (folder.UniqueId == library.RootFolder.UniqueId) { // We are setting the Pages library's root folder's welcome page, so let's assume this means we also need to set it as the website's welcome page as well var webRootFolder = library.ParentWeb.RootFolder; webRootFolder.WelcomePage = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", publishingPages.PubWeb.PagesListName, publishingPage.Name); webRootFolder.Update(); EnsureFolderPublish(folder); } } EnsurePageCheckInAndPublish(publishingPage); } else { this.logger.Info("Folder maker is skipping the creation of page '{0}' because it already exists.", existingPage.Url); if (this.defaultPageWebPartIndex.GetDefaultWebPartsForPageUrl(existingPage.Url) != null) { // If there are some registered on the index, add the // webparts to the page (make sure to checkout/checkin). this.logger.Info("Ensuring the existance of the webparts on page '{0}'.", existingPage.Url); this.EnsurePageCheckOut(existingPage); this.EnsureWebpartsOnPage(existingPage); EnsurePageCheckInAndPublish(existingPage); } } } } }
private void DefaultPageLayoutProcess(SPWebEventProperties properties) { PageLayout _pageLayout; try { using (SPSite site = new SPSite(properties.SiteId)) { using (SPWeb web = site.OpenWeb()) { PublishingSite pubSiteCollection = new PublishingSite(site); PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(properties.Web); //check if pagelayout to be defaulted already exists in AvailablePageLayouts _pageLayout = (from _pl in publishingWeb.GetAvailablePageLayouts() where _pl.Name == defaultPageLayout select _pl).FirstOrDefault(); //if exists if (_pageLayout != null) { publishingWeb.SetDefaultPageLayout(_pageLayout, true); publishingWeb.Update(); } else //if does not exist { //get all AvailablePageLayouts PageLayout[] _allpageLayout = publishingWeb.GetAvailablePageLayouts(); PageLayout[] plarray = new PageLayout[_allpageLayout.Length + 1]; int ipl = -1; //transfer existing pagelayouts in AvailablePageLayouts to PageLayout[] foreach (PageLayout _itempl in _allpageLayout) { ipl++; plarray[ipl] = _itempl; } //PageLayout to be defaulted to _pageLayout = pubSiteCollection.PageLayouts["/_catalogs/masterpage/" + defaultPageLayout]; ipl++; //add to the PageLayout array plarray[ipl] = _pageLayout; //reset AvailablePageLayouts publishingWeb.SetAvailablePageLayouts(plarray, true); publishingWeb.Update(); //set DefaultPageLayout publishingWeb.SetDefaultPageLayout(_pageLayout, true); publishingWeb.Update(); web.Update(); } //Swap the page layout of the default.aspx page SwapPageLayout(publishingWeb, _pageLayout, web.Site.RootWeb.ContentTypes[_pageLayout.AssociatedContentType.Id]); } } } catch (Exception ex) { Logger.WriteLog("WebProvisioning.cs - DefaultPageLayoutProcess: " + ex.Message + " " + ex.StackTrace); } }
public void DefineDefaultHome(SPWeb web, PublishingSite pubSite, PublishingWeb pubWeb) { pubWeb.DefaultPage = web.GetFile("default.aspx"); pubWeb.Update(); }
/// <summary> /// Configures a page layout /// </summary> /// <param name="site">The site</param> /// <param name="pageLayoutInfo">The page layout info</param> /// <returns>The page layout</returns> public PageLayout EnsurePageLayout(SPSite site, PageLayoutInfo pageLayoutInfo) { var publishingSite = new PublishingSite(site); var pageLayout = this.GetPageLayout(publishingSite, pageLayoutInfo.Name, true); if (pageLayoutInfo.AssociatedContentTypeId != null) { var contentTypeId = site.RootWeb.ContentTypes.BestMatch(pageLayoutInfo.AssociatedContentTypeId); var ct = site.RootWeb.ContentTypes[contentTypeId]; // Applies the preview picture of the page layout if (pageLayoutInfo.PreviewImageUrl != null) { Uri previewImageUrl; if (!pageLayoutInfo.PreviewImageUrl.IsAbsoluteUri) { previewImageUrl = new Uri(new Uri(site.Url), pageLayoutInfo.PreviewImageUrl); } else { previewImageUrl = pageLayoutInfo.PreviewImageUrl; } pageLayout.PreviewImageUrl = previewImageUrl.AbsoluteUri; } // Update the publishing associated content type pageLayout.AssociatedContentType = ct; pageLayout.Update(); } return pageLayout; }
private PublishingWeb GetPublishingSiteFromWeb(SPWeb web) { PublishingWeb result = null; if (web == null) throw new ArgumentNullException("web"); var pubSite = new PublishingSite(web.Site); if (PublishingWeb.IsPublishingWeb(web)) { result = PublishingWeb.GetPublishingWeb(web); } return result; }
/// <summary> /// Get the page layout /// </summary> /// <param name="publishingSite">the current publishing site</param> /// <param name="pageLayoutName">the page layout name</param> /// <param name="excludeObsolete">exclude obsolete page layout</param> /// <returns>the page layout</returns> public PageLayout GetPageLayout(PublishingSite publishingSite, string pageLayoutName, bool excludeObsolete) { return publishingSite.GetPageLayouts(excludeObsolete).Cast<PageLayout>().FirstOrDefault(pageLayout => pageLayout.Name == pageLayoutName); }