private void CreatePartnerTabbedPage(SPWeb web, SPList sitesList) { // Create a new page for listing Partner Site Collections if (PublishingWeb.IsPublishingWeb(web)) { PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web); PublishingPageCollection availablePages = pubWeb.GetPublishingPages(); PublishingPage partnerSitesPage = availablePages[Constants.PartnerSitesPageUrl]; if (partnerSitesPage == null) { // The Partner Sites page should be based on the same layout as the top sites page. PublishingPage topSitesPage = availablePages[Constants.TopSitesPageUrl]; partnerSitesPage = availablePages.Add(Constants.PartnerSitesFileName, topSitesPage.Layout); partnerSitesPage.ListItem[titleFieldId] = Constants.PartnerSitesTile; // We can not use the Field Id of the the Description field, because it is not static. partnerSitesPage.ListItem[Constants.DescriptionField] = Resources.PartnerSitePageDescription; partnerSitesPage.Update(); SPFile partnerSitesPageFile = web.GetFile(partnerSitesPage.Url); AddListViewWebPartToPage(sitesList, partnerSitesPage, partnerSitesPageFile); // Add a tab to the Tabs control. SPListItem newTab = web.Lists[Constants.TabsList].Items.Add(); newTab[Constants.TabNameField] = Constants.PartnersTabName; newTab[Constants.PageField] = Constants.PartnerSitesFileName; newTab[Constants.TooltipField] = Constants.PartnerSitesTooltip; newTab.Update(); } } }
protected override IEnumerable <PageLayout> RetrieveDataObjects() { List <PageLayout> layouts = new List <PageLayout>(); SPWeb web = null; if (Web != null) { web = Web.Read(); if (!PublishingWeb.IsPublishingWeb(web)) { throw new ArgumentException("The specified web is not a publishing web."); } AssignmentCollection.Add(web); AssignmentCollection.Add(web.Site); } switch (ParameterSetName) { case "PageLayout": foreach (SPPageLayoutPipeBind pipeBind in PageLayout) { PageLayout layout = pipeBind.Read(web); SPContentType ct1 = null; if (AssociatedContentType != null) { ct1 = AssociatedContentType.Read(layout.ListItem.Web); } if (ct1 == null || ct1.Id == layout.AssociatedContentType.Id) { WriteResult(layout); } } break; case "SPWeb": PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web); SPContentType ct2 = null; if (AssociatedContentType != null) { ct2 = AssociatedContentType.Read(web); } if (ct2 == null) { WriteResult(pubWeb.GetAvailablePageLayouts()); } else { WriteResult(pubWeb.GetAvailablePageLayouts(ct2.Id)); } break; default: break; } return(null); }
/// <summary> /// Establece la Página de bienveniva de un sitiio /// </summary> /// <param name="web">Objeto SPWeb </param> /// <param name="welcomePage"> Url de la página de bienvenida</param> /// <returns></returns> public static bool SetWelcomePage(this SPWeb web, string welcomePage) { var result = true; try { if (PublishingWeb.IsPublishingWeb(web)) { var publishingWeb = PublishingWeb.GetPublishingWeb(web); var homeFile = web.GetFile(welcomePage); publishingWeb.DefaultPage = homeFile; publishingWeb.Update(); } else { web.RootFolder.WelcomePage = welcomePage; } web.Update(); } catch (Exception) { result = false; } return(result); }
public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPWeb web = properties.Feature.Parent as SPWeb; //if the web of type MLGSchool, set its MasterURL and Custom MasterURl if (string.Compare(web.WebTemplate, "MLGSchool", true) == 0) { try { string masterURL = web.ServerRelativeUrl + masterPageName; web.MasterUrl = masterURL; web.CustomMasterUrl = masterURL; web.Update(); } catch { } } else { //in case this is not a school site, check if it is a publishing web, //and if so set the MasterURL, and customMusterURl to inherit from the parent site. try { if (PublishingWeb.IsPublishingWeb(web)) { PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web); pWeb.MasterUrl.SetInherit(true, true); pWeb.CustomMasterUrl.SetInherit(true, true); pWeb.Update(); } } catch { } } }
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; } }
public bool IsPublishingWeb(SPWebInstance web) { if (web == null) { throw new JavaScriptException(this.Engine, "Error", "A SPWeb must be supplied as the first parameter."); } return(PublishingWeb.IsPublishingWeb(web.Web)); }
public static void EnsurePublishingWorkflows(SPWeb web, bool useSAMLWorkflow, bool remove) { if (PublishingWeb.IsPublishingWeb(web)) { PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web); if (pubweb != null) { string listNames = GlobalSettingsHelper.GetValue(ListConstants.EnablePublishingApprovalWorkflowOnLists); if (!string.IsNullOrEmpty(listNames)) { string[] lists = listNames.ToLower().Split(new char[] { ',' }); foreach (string listName in lists) { SPList list = null; switch (listName) { case ("pages"): list = pubweb.PagesList; break; case ("images"): list = pubweb.ImagesLibrary; break; case ("documents"): list = pubweb.DocumentsLibrary; break; } if (list != null) { if (remove) { WorkflowHelper2013.RemoveApprovalWorkflowOnList(web, list, useSAMLWorkflow); } else { List <WorkflowHelper2013.WorkflowStartEventType> events = new List <WorkflowHelper2013.WorkflowStartEventType>() { WorkflowHelper2013.WorkflowStartEventType.Manual }; WorkflowHelper2013.EnsureApprovalWorkflowOnList(web, list, events, useSAMLWorkflow); } } } } } } else { throw new SPException("This feature can only be enabled on a Publishing Web. However you can configure the approval workflows thru list workflow settings."); } }
public List <string> GetAllPagesInWeb(SPWeb web) { if (PublishingWeb.IsPublishingWeb(web)) { return(GetAllPublishingPages(PublishingWeb.GetPublishingWeb(web))); } else { return(GetAllPagesFromRoot(web)); } }
private void InitializeObject(SPWeb web) { SPSite cachedSuperUserSite = null; if (HttpContext.Current != null) { cachedSuperUserSite = HttpContext.Current.Items["SuperUserSite"] as SPSite; if (cachedSuperUserSite != null && cachedSuperUserSite.ID != web.Site.ID) { HttpContext.Current.Items["SuperUserSite"] = null; } } try { if (PublishingWeb.IsPublishingWeb(web)) { PublishingWeb currentWeb = PublishingWeb.GetPublishingWeb(web); VariationLabel currentLabel = GetVariationLabel(currentWeb); if (currentLabel != null) { this.IsVariationWeb = true; this.IsSource = currentLabel.IsSource; this.TopWebServerRelativeUrl = new Uri(currentLabel.TopWebUrl).AbsolutePath; this.VariationLabel = currentLabel.Title; this.PagesListName = currentWeb.PagesListName; int lcid; if (Int32.TryParse(currentLabel.Locale, out lcid)) { this.Culture = CultureInfo.GetCultureInfo(lcid); } else { this.Culture = CultureInfo.GetCultureInfo(currentLabel.Language); } } } if (!this.IsVariationWeb) { this.TopWebServerRelativeUrl = web.Site.ServerRelativeUrl; this.VariationLabel = String.Empty; this.PagesListName = "Pages"; this.Culture = web.UICulture; } } finally { // avoid messing up calls to publishing web API in the same HTTP request (FileNotFoundException) // where SuperUserSite should be reserved for current site collection // https://sharepoint.stackexchange.com/questions/83242 if (HttpContext.Current != null && (cachedSuperUserSite == null || cachedSuperUserSite.ID != web.Site.ID)) { HttpContext.Current.Items["SuperUserSite"] = cachedSuperUserSite; } } }
public PageLayout Read(SPWeb web) { if (web == null) { return(Read((PublishingWeb)null)); } if (!PublishingWeb.IsPublishingWeb(web)) { throw new ArgumentException("The specified web is not a publishing web."); } PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web); return(Read(pubWeb)); }
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); }
public static void GetNavigation(XmlDocument xmlDoc, SPWeb web, bool includeChildren) { if (PublishingWeb.IsPublishingWeb(web)) { PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web); XmlElement webNode = (XmlElement)xmlDoc.DocumentElement.AppendChild(xmlDoc.CreateElement("Web")); webNode.SetAttribute("serverRelativeUrl", web.ServerRelativeUrl); GetNavigation(pubweb, webNode); } if (includeChildren) { foreach (SPWeb childWeb in web.Webs) { GetNavigation(xmlDoc, childWeb, true); } } }
private void SetTitleDescriptionAndGroupValues(ContentTypeInfo contentTypeInfo, SPContentType contentType) { //// Get a list of the available languages and end with the main language var web = contentType.ParentWeb; var availableLanguages = web.SupportedUICultures.Reverse().ToList(); // If it's a publishing web, add the variation labels as available languages if (PublishingWeb.IsPublishingWeb(web) && this.variationHelper.IsVariationsEnabled(web.Site)) { var labels = this.variationHelper.GetVariationLabels(web.Site); if (labels.Count > 0) { // Predicate to check if the web contains the label language in it's available languages Func <VariationLabel, bool> notAvailableWebLanguageFunc = (label) => !availableLanguages.Any(lang => lang.Name.Equals(label.Language, StringComparison.OrdinalIgnoreCase)); // Get the label languages that aren't already in the web's available languages var labelLanguages = labels .Where(notAvailableWebLanguageFunc) .Select(label => new CultureInfo(label.Language)); availableLanguages.AddRange(labelLanguages); } } // If multiple languages are enabled, since we have a full ContentTypeInfo object, we want to populate // all alternate language labels for the Content Type foreach (CultureInfo availableLanguage in availableLanguages) { var previousUiCulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentUICulture = availableLanguage; contentType.Name = this.resourceLocator.GetResourceString(contentTypeInfo.ResourceFileName, contentTypeInfo.DisplayNameResourceKey); contentType.Description = this.resourceLocator.GetResourceString(contentTypeInfo.ResourceFileName, contentTypeInfo.DescriptionResourceKey); contentType.Description = this.resourceLocator.Find(contentTypeInfo.ResourceFileName, contentTypeInfo.DescriptionResourceKey, availableLanguage.LCID); contentType.Group = this.resourceLocator.GetResourceString(contentTypeInfo.ResourceFileName, contentTypeInfo.GroupResourceKey); Thread.CurrentThread.CurrentUICulture = previousUiCulture; } contentType.Update(); }
public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPWeb currentWeb = properties.Feature.Parent as SPWeb; // The Promotions feature should only be activated on a Publishing Site. if (PublishingWeb.IsPublishingWeb(currentWeb)) { PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(currentWeb); SPFile defaultPage = publishingWeb.DefaultPage; // If the default page doesn't exist, it needs to be created first. if (defaultPage == null) { defaultPage = CreateNewWelcomePage(currentWeb, publishingWeb, defaultPage); } else { defaultPage.CheckOut(); } try { // Create a custom View that displays only Promotion Pages. SPList pagesList = currentWeb.Lists[PagesList]; SPView promotionsOnlyView = CreatePromotionsOnlyView(currentWeb, pagesList); // Add a list view Web part to display Promotions Only AddListViewWebPartToPage(defaultPage, pagesList, promotionsOnlyView); } finally { defaultPage.CheckIn(CheckInComment); defaultPage.Publish(CheckInComment); } // Save the URL of the site where this feature is being activated. This settings will be used at runtime. SetUrlInConfig(currentWeb); // Register the Promotion RegisterPromotionRepositoryTypeMapping(); } }
public override void WebProvisioned(SPWebEventProperties properties) { base.WebProvisioned(properties); using (SPSite site = new SPSite(properties.Web.Site.ID)) { using (SPWeb web = site.AllWebs[properties.WebId]) { if (PublishingWeb.IsPublishingWeb(web)) { SPSecurity.RunWithElevatedPrivileges(delegate() { DefaultMasterPageProcess(properties); DefaultPageLayoutProcess(properties); MUIProcess(properties); DefaultNavigation(properties); CreateFooterList(properties); }); } } } }
public static OutputQueue SetLookoutAsMySiteHomePage(string mySiteWebUrl) { var output = new OutputQueue(); try { using (var site = new SPSite(mySiteWebUrl)) { if (site != null) { using (var web = site.OpenWeb()) { if (web != null) { if (PublishingWeb.IsPublishingWeb(web)) { var publishingWeb = PublishingWeb.GetPublishingWeb(web); var lookoutPageFile = web.GetFile("Lookout.aspx"); publishingWeb.DefaultPage = lookoutPageFile; publishingWeb.Update(); publishingWeb.Close(); } else { var rootFolder = web.RootFolder; rootFolder.WelcomePage = "Lookout.aspx"; rootFolder.Update(); web.Update(); } } } } } } catch (Exception exception) { output.Add(string.Format(CultureInfo.CurrentCulture, Exceptions.ErrorSettingLookoutHomePage, exception.Message), OutputType.Error, string.Empty, exception); } return(output); }
/// <summary> /// Enumerates the specified web. /// </summary> /// <param name="site">The site.</param> /// <param name="web">The web.</param> /// <param name="enumerateSubWebs">if set to <c>true</c> [enumerate sub webs].</param> private void Enumerate(SPSite site, SPWeb web, bool enumerateSubWebs) { OnSPWebEnumerated(site, web); if (SPListEnumerated != null) { for (int i = 0; i < web.Lists.Count; i++) { OnSPListEnumerated(site, web, web.Lists[i]); } } #if MOSS if (PublishingPageEnumerated != null) { if (PublishingWeb.IsPublishingWeb(web)) { PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web); foreach (PublishingPage page in pubWeb.GetPublishingPages()) { OnPublishingPageEnumerated(site, web, page); } } } #endif if (enumerateSubWebs) { foreach (SPWeb subWeb in web.Webs) { try { Enumerate(site, subWeb, enumerateSubWebs); } finally { subWeb.Dispose(); } } } }
public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPWeb web = properties.Feature.Parent as SPWeb; if (web != null) { if (PublishingWeb.IsPublishingWeb(web)) { PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web); PublishingPage page = pubWeb.GetPublishingPages()[PartnerLandingPageUrl]; if (page == null) { SPContentTypeId contentTypeId = new SPContentTypeId(welcomePageLayoutContentTypeId); PageLayout[] layouts = pubWeb.GetAvailablePageLayouts(contentTypeId); PageLayout welcomePageLayout = layouts[0]; page = pubWeb.GetPublishingPages().Add(PartnerLandingPageFileName, welcomePageLayout); } else { page.CheckOut(); } page.ListItem[titleFieldId] = PartnerLandingPageTile; page.ListItem[DescriptionField] = Resources.PageDescription; page.ListItem[pageContentFieldId] = Resources.PageContent; page.ListItem[partnerSpecificContentFieldId] = Resources.PartnerSpecificContent; page.Update(); SPFile welcomeFile = web.GetFile(page.Url); pubWeb.DefaultPage = welcomeFile; pubWeb.Update(); page.CheckIn(Resources.CheckInValue); } } }
public static PublishingPage CreatePage(this SPWeb web, string pageName, string pageLayoutName) { if (!PublishingWeb.IsPublishingWeb(web)) { return(null); } PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web); PageLayout pageLayout = publishingWeb.GetAvailablePageLayouts().FirstOrDefault( page => page.Name.Equals(pageLayoutName, StringComparison.InvariantCultureIgnoreCase)); if (pageLayout == null) { return(null); //throw new SPException(string.Format("Page layout with name {0} is not found.", pageLayoutName)); } PublishingPage newPage = publishingWeb.AddPublishingPage(pageName, pageLayout); return(newPage); }
/// <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); }
private static bool IsPublishingSite(ISharePointCommandContext context) { bool isPublishingSite = PublishingWeb.IsPublishingWeb(context.Web); return(isPublishingSite); }
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); }
public PageLayout Read(PublishingWeb pubWeb) { // We don't dispose here as we'll add these objects // to the SPAssignmentCollection SPSite site = null; SPWeb web = null; if (pubWeb == null && _isAbsoluteUrl) { site = new SPSite(_fileUrl); web = site.OpenWeb(); if (!PublishingWeb.IsPublishingWeb(web)) { throw new ArgumentException("The specified web is not a publishing web."); } pubWeb = PublishingWeb.GetPublishingWeb(web); } else if (pubWeb == null && !_isAbsoluteUrl) { throw new FileNotFoundException("The specified layout could not be found.", _fileUrl); } else { web = pubWeb.Web; } PageLayout file = null; if (_isAbsoluteUrl) { foreach (PageLayout lo in pubWeb.GetAvailablePageLayouts()) { if (lo.ListItem.Web.Site.MakeFullUrl(lo.ServerRelativeUrl.ToLowerInvariant()) == _fileUrl.ToLowerInvariant()) { file = lo; break; } } } else { foreach (PageLayout lo in pubWeb.GetAvailablePageLayouts()) { if (lo.Name.ToLowerInvariant() == _fileUrl.ToLowerInvariant()) { file = lo; break; } } } if (file == null) { if (web != null) { web.Dispose(); } if (site != null) { site.Dispose(); } throw new SPCmdletPipeBindException(string.Format("SPPageLayoutPipeBind object not found ({0})", _fileUrl)); } return(file); }
private void ResetSPTheme(SPWeb web, bool resetChildren) { try { // Store some variables for later use string tempFolderName = Guid.NewGuid().ToString("N").ToUpper(); string themedFolderName = SPUrlUtility.CombineUrl(web.Site.ServerRelativeUrl, "/_catalogs/theme/Themed"); string themesUrlForWeb = ThmxTheme.GetThemeUrlForWeb(web); if (string.IsNullOrEmpty(themesUrlForWeb)) { Logger.WriteWarning("The web {0} does not have a theme set and will be ignored.", web.Url); return; } if (!web.IsRootWeb) { string themesUrlForParentWeb = ThmxTheme.GetThemeUrlForWeb(web.ParentWeb); if (themesUrlForWeb.ToLower() == themesUrlForParentWeb.ToLower()) { Logger.WriteWarning("The web {0} inherits it's theme from it's parent. The theme will not be reset.", web.Url); return; } } // Open the existing theme ThmxTheme webThmxTheme = ThmxTheme.Open(web.Site, themesUrlForWeb); // Generate a new theme using the settings defined for the existing theme // (this will generate a temporary theme folder that we'll need to delete) webThmxTheme.GenerateThemedStyles(true, web.Site.RootWeb, tempFolderName); // Apply the newly generated theme to the web ThmxTheme.SetThemeUrlForWeb(web, SPUrlUtility.CombineUrl(themedFolderName, tempFolderName) + "/theme.thmx", true); // Delete the temp folder created earlier web.Site.RootWeb.GetFolder(SPUrlUtility.CombineUrl(themedFolderName, tempFolderName)).Delete(); // Reset the theme URL just in case it has changed (sometimes it will) using (SPSite site = new SPSite(web.Site.ID)) using (SPWeb web2 = site.OpenWeb(web.ID)) { string updatedThemesUrlForWeb = ThmxTheme.GetThemeUrlForWeb(web2); if (resetChildren) { bool isPublishingWeb = false; #if MOSS isPublishingWeb = PublishingWeb.IsPublishingWeb(web2); #endif // Set all child webs to inherit. if (isPublishingWeb) { #if MOSS PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web2); pubWeb.ThemedCssFolderUrl.SetValue(pubWeb.Web.ThemedCssFolderUrl, true); #endif } else { ResetChildWebs(web2, updatedThemesUrlForWeb); } } else { if (themesUrlForWeb != updatedThemesUrlForWeb) { UpdateInheritingWebs(web2, themesUrlForWeb, updatedThemesUrlForWeb); } } } } finally { if (web != null) { web.Site.Dispose(); } } }
/// <summary> /// Enumerates the collection. /// </summary> /// <param name="pubWeb">The publishing web.</param> /// <param name="isGlobal">if set to <c>true</c> [is global].</param> /// <param name="nodes">The nodes.</param> /// <param name="xmlParentNode">The XML parent node.</param> private static void EnumerateCollection(PublishingWeb pubWeb, bool isGlobal, SPNavigationNodeCollection nodes, XmlElement xmlParentNode) { if (nodes == null || nodes.Count == 0) { return; } foreach (SPNavigationNode node in nodes) { NodeTypes type = NodeTypes.None; if (node.Properties["NodeType"] != null && !string.IsNullOrEmpty(node.Properties["NodeType"].ToString())) { type = (NodeTypes)Enum.Parse(typeof(NodeTypes), node.Properties["NodeType"].ToString()); } if (isGlobal) { if ((type == NodeTypes.Area && !pubWeb.Navigation.GlobalIncludeSubSites) || (type == NodeTypes.Page && !pubWeb.Navigation.GlobalIncludePages)) { continue; } } else { if ((type == NodeTypes.Area && !pubWeb.Navigation.CurrentIncludeSubSites) || (type == NodeTypes.Page && !pubWeb.Navigation.CurrentIncludePages)) { continue; } } XmlElement xmlChildNode = xmlParentNode.OwnerDocument.CreateElement("Node"); xmlParentNode.AppendChild(xmlChildNode); xmlChildNode.SetAttribute("Id", node.Id.ToString()); xmlChildNode.SetAttribute("Title", node.Title); // Set the default visibility to true. xmlChildNode.SetAttribute("IsVisible", node.IsVisible.ToString()); #region Determine Visibility if (type == NodeTypes.Area) { SPWeb web = null; try { string name = node.Url.Trim('/'); if (name.Length != 0 && name.IndexOf("/") > 0) { name = name.Substring(name.LastIndexOf('/') + 1); } try { web = pubWeb.Web.Webs[name]; } catch (ArgumentException) { } if (web != null && web.Exists && web.ServerRelativeUrl.ToLower() == node.Url.ToLower() && PublishingWeb.IsPublishingWeb(web)) { PublishingWeb tempPubWeb = PublishingWeb.GetPublishingWeb(web); if (isGlobal) { xmlChildNode.SetAttribute("IsVisible", tempPubWeb.IncludeInGlobalNavigation.ToString()); } else { xmlChildNode.SetAttribute("IsVisible", tempPubWeb.IncludeInCurrentNavigation.ToString()); } } } finally { if (web != null) { web.Dispose(); } } } else if (type == NodeTypes.Page) { PublishingPage page = null; try { page = pubWeb.GetPublishingPages()[node.Url]; } catch (ArgumentException) { } if (page != null) { if (isGlobal) { xmlChildNode.SetAttribute("IsVisible", page.IncludeInGlobalNavigation.ToString()); } else { xmlChildNode.SetAttribute("IsVisible", page.IncludeInCurrentNavigation.ToString()); } } } #endregion XmlElement xmlProp = xmlParentNode.OwnerDocument.CreateElement("Url"); xmlProp.InnerText = node.Url; xmlChildNode.AppendChild(xmlProp); foreach (DictionaryEntry d in node.Properties) { xmlProp = xmlParentNode.OwnerDocument.CreateElement(d.Key.ToString()); xmlProp.InnerText = d.Value.ToString(); xmlChildNode.AppendChild(xmlProp); } EnumerateCollection(pubWeb, isGlobal, node.Children, xmlChildNode); } }
/// <summary> /// Fixes the pages page layout url so that it points to the page layout in the container site collections master page gallery. /// </summary> /// <param name="publishingWeb">The target publishing web.</param> /// <param name="pageName">Name of the page.</param> /// <param name="pageLayoutUrl">The page layout URL.</param> /// <param name="searchRegex">The search regex.</param> /// <param name="replaceString">The replace string.</param> /// <param name="fixContact">if set to <c>true</c> [fix contact].</param> /// <param name="test">if set to <c>true</c> [test].</param> public static void FixPages(PublishingWeb publishingWeb, string pageName, string pageLayoutUrl, Regex searchRegex, string replaceString, bool fixContact, bool test) { if (!PublishingWeb.IsPublishingWeb(publishingWeb.Web)) { return; } PublishingPageCollection pages; int tryCount = 0; while (true) { try { tryCount++; pages = publishingWeb.GetPublishingPages(); break; } catch (InvalidPublishingWebException) { // The following is meant to deal with a timing issue when using this method in conjuction with other commands. When // used independently this should be unnecessary. if (tryCount > 4) { throw; } Thread.Sleep(10000); SPWeb web = publishingWeb.Web; SPSite site = web.Site; string url = site.MakeFullUrl(web.ServerRelativeUrl); site.Close(); site.Dispose(); web.Close(); web.Dispose(); publishingWeb.Close(); site = new SPSite(url); web = site.OpenWeb(Utilities.GetServerRelUrlFromFullUrl(url)); publishingWeb = PublishingWeb.GetPublishingWeb(web); } } foreach (PublishingPage page in pages) { if (!(string.IsNullOrEmpty(pageName) || page.Name.ToLower() == pageName.ToLower())) { continue; } if (page.ListItem[FieldId.PageLayout] == null) { continue; } Logger.Write("Progress: Begin processing {0}.", page.Url); Logger.Write("Progress: Current layout set to {0}.", page.ListItem[FieldId.PageLayout].ToString()); // Can't edit items that are checked out. if (Utilities.IsCheckedOut(page.ListItem) && !Utilities.IsCheckedOutByCurrentUser(page.ListItem)) { Logger.WriteWarning("WARNING: Page is already checked out by another user - skipping."); continue; } SPFieldUrlValue url; if (string.IsNullOrEmpty(pageLayoutUrl)) { if (searchRegex == null) { if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim())) { Logger.WriteWarning("WARNING: Current page layout is empty - skipping. Use the 'pagelayout' parameter to set a page layout."); continue; } // We didn't get a layout url passed in or a regular expression so try and fix the existing url url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString()); if (string.IsNullOrEmpty(url.Url) || url.Url.IndexOf("/_catalogs/") < 0) { Logger.WriteWarning("WARNING: Current page layout does not point to a _catalogs folder or is empty - skipping. Use the 'pagelayout' parameter to set a page layout Layout Url: {0}", url.ToString()); continue; } string newUrl = publishingWeb.Web.Site.ServerRelativeUrl.TrimEnd('/') + url.Url.Substring(url.Url.IndexOf("/_catalogs/")); string newDesc = publishingWeb.Web.Site.MakeFullUrl(newUrl); if (url.Url.ToLowerInvariant() == newUrl.ToLowerInvariant()) { Logger.Write("Progress: Current layout matches new evaluated layout - skipping."); continue; } url.Url = newUrl; url.Description = newDesc; } else { if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim())) { Logger.Write("Progress: Current page layout is empty - skipping. Use the pagelayout parameter to set a page layout."); } // A regular expression was passed in so use it to fix the page layout url if we find a match. if (searchRegex.IsMatch((string)page.ListItem[FieldId.PageLayout])) { url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString()); string newUrl = searchRegex.Replace((string)page.ListItem[FieldId.PageLayout], replaceString); if (url.ToString().ToLowerInvariant() == newUrl.ToLowerInvariant()) { Logger.Write("Progress: Current layout matches new evaluated layout - skipping."); continue; } url = new SPFieldUrlValue(newUrl); } else { Logger.Write("Progress: Existing page layout url does not match provided regular expression - skipping."); continue; } } } else { // The user passed in an url string so use it. if (pageLayoutUrl.ToLowerInvariant() == (string)page.ListItem[FieldId.PageLayout]) { Logger.Write("Progress: Current layout matches provided layout - skipping."); continue; } url = new SPFieldUrlValue(pageLayoutUrl); } string fileName = url.Url.Substring(url.Url.LastIndexOf('/')); // Make sure that the URLs are server relative instead of absolute. //if (url.Description.ToLowerInvariant().StartsWith("http")) // url.Description = Utilities.GetServerRelUrlFromFullUrl(url.Description) + fileName; //if (url.Url.ToLowerInvariant().StartsWith("http")) // url.Url = Utilities.GetServerRelUrlFromFullUrl(url.Url) + fileName; if (page.ListItem[FieldId.PageLayout] != null && url.ToString().ToLowerInvariant() == page.ListItem[FieldId.PageLayout].ToString().ToLowerInvariant()) { continue; // No difference detected so move on. } Logger.Write("Progress: Changing layout url from \"{0}\" to \"{1}\"", page.ListItem[FieldId.PageLayout].ToString(), url.ToString()); if (fixContact) { SPUser contact = null; try { contact = page.Contact; } catch (SPException) { } if (contact == null) { Logger.Write("Progress: Page contact ('{0}') does not exist - assigning current user as contact.", page.ListItem[FieldId.Contact].ToString()); page.Contact = publishingWeb.Web.CurrentUser; if (!test) { page.ListItem.SystemUpdate(); } } } if (test) { continue; } try { bool publish = false; if (!Utilities.IsCheckedOut(page.ListItem)) { page.CheckOut(); publish = true; } page.ListItem[FieldId.PageLayout] = url; page.ListItem.UpdateOverwriteVersion(); if (publish) { Common.Lists.PublishItems itemPublisher = new Common.Lists.PublishItems(); itemPublisher.PublishListItem(page.ListItem, page.ListItem.ParentList, false, "Automated fix of publishing pages page layout URL.", null, null); } } catch (Exception ex) { Logger.WriteException(new ErrorRecord(ex, null, ErrorCategory.NotSpecified, page)); } } }
public void Application_Error(object sender, EventArgs e) { try { Guid errorGuid = GetCurrentCorrelationToken(); BaseComponent.Error("Apploication_ErrorID: " + errorGuid); HttpContext ctx = HttpContext.Current; if (SPContext.Current != null) { string path = System.Configuration.ConfigurationSettings.AppSettings["SiteRootUrl"].ToString(); Exception ex = ctx.Server.GetLastError(); if (ex == null) { int count = ctx.AllErrors.Length; if (count > 0) { ex = ctx.AllErrors[count - 1]; } } string error_mes = ""; if (ex != null) { error_mes = ex.Message; if (ex.InnerException != null) { Exception iex = ex.InnerException; error_mes = iex.Message; } } //一定要记得清除错误 ctx.Server.ClearError(); ctx.ClearError(); if (!string.IsNullOrWhiteSpace(path)) { string pageUrl = ""; using (SPSite spSite = new SPSite(path)) { using (SPWeb spWeb = spSite.OpenWeb()) { PublishingWeb publishingWeb = null; if (spWeb != null && PublishingWeb.IsPublishingWeb(spWeb)) { publishingWeb = PublishingWeb.GetPublishingWeb(spWeb); SPList spList = publishingWeb.PagesList; SPFile spFile = spWeb.GetFile("" + spList.RootFolder.ServerRelativeUrl + "/errorpage/errorpage.aspx"); if (spFile != null) { pageUrl = spFile.ServerRelativeUrl; } } } } if (!String.IsNullOrEmpty(pageUrl)) { ctx.Response.Redirect(pageUrl + "?errorID=" + errorGuid.ToString()); } } return; } } catch (Exception ex) { } }
protected override IEnumerable <PublishingPage> RetrieveDataObjects() { List <PublishingPage> publishingPages = new List <PublishingPage>(); switch (ParameterSetName) { case "SPWeb": foreach (SPWebPipeBind webPipe in Web) { SPWeb web = webPipe.Read(); WriteVerbose("Getting publishing page from " + web.Url); if (!PublishingWeb.IsPublishingWeb(web)) { WriteWarning(string.Format("Web \"{0}\" is not a publishing web and will be skipped.", web.Url)); continue; } PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web); if (PageName == null || PageName.Length == 0) { foreach (PublishingPage page in pubWeb.GetPublishingPages()) { publishingPages.Add(page); } } else { foreach (string pageName in PageName) { string pageUrl = string.Format("{0}/{1}/{2}", web.Url.TrimEnd('/'), pubWeb.PagesListName, pageName.Trim('/')); try { PublishingPage page = pubWeb.GetPublishingPage(pageUrl); if (page != null) { publishingPages.Add(page); } else { WriteWarning("Could not locate the specified page: " + pageUrl); } } catch (ArgumentException) { WriteWarning("Could not locate the specified page: " + pageUrl); } } } } break; case "SPFile": foreach (SPFilePipeBind filePipe in Identity) { SPFile file = filePipe.Read(); if (!PublishingWeb.IsPublishingWeb(file.Web)) { WriteWarning(string.Format("Web \"{0}\" is not a publishing web and will be skipped.", file.Web.Url)); continue; } WriteVerbose("Getting publishing page from " + file.Url); try { PublishingPage page = null; if (file.Exists) { page = PublishingPage.GetPublishingPage(file.Item); } if (page != null) { publishingPages.Add(page); } else { WriteWarning("Could not locate the specified page: " + file.Url); } } catch (ArgumentException) { WriteWarning("Could not locate the specified page: " + file.Url); } } break; } foreach (PublishingPage page in publishingPages) { AssignmentCollection.Add(page.PublishingWeb.Web); AssignmentCollection.Add(page.PublishingWeb.Web.Site); WriteResult(page); } return(null); }