Exemple #1
0
        private static void ProcessNewPageDefaultSettings(
            WebModelHost webModelHost,
            PublishingWeb publishingWeb,
            PageLayoutAndSiteTemplateSettingsDefinition definition,
            List <ListItem> pageLayouts)
        {
            var web     = publishingWeb.Web;
            var context = web.Context;

            if (definition.InheritDefaultPageLayout.HasValue && definition.InheritDefaultPageLayout.Value)
            {
                SetPropertyBagValue(web, "__DefaultPageLayout", "__inherit");
            }
            else if (definition.UseDefinedDefaultPageLayout.HasValue && definition.UseDefinedDefaultPageLayout.Value)
            {
                var selectedLayoutName = definition.DefinedDefaultPageLayout;
                var targetLayout       = pageLayouts.FirstOrDefault(t => t["FileLeafRef"].ToString().ToUpper() == selectedLayoutName.ToUpper());

                if (targetLayout != null)
                {
                    var resultString = CreateLayoutXmlString(targetLayout);
                    SetPropertyBagValue(web, "__DefaultPageLayout", resultString);
                }
            }
        }
Exemple #2
0
        /// <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);
        }
Exemple #3
0
        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();
                }
            }
        }
        private static void AddPublishingPage(ClientContext context, PublishingWeb webPub, ListItemCollection allPageLayouts, OfficeDevPnP.Core.Framework.Provisioning.Model.PublishingPage page)
        {
            ListItem layout = null;

            //try to get layout by Title
            layout = allPageLayouts.Where(x => x["Title"] != null && x["Title"].ToString().Equals(page.Layout)).FirstOrDefault();

            //try to get layout by DisplayName
            if (layout == null)
            {
                layout = allPageLayouts.Where(x => x.DisplayName == page.Layout).FirstOrDefault();
            }

            //we need to have a layout for a publishing page
            if (layout == null)
            {
                throw new ArgumentNullException(string.Format("Layout '{0}' for page {1} can not be found.", page.Layout, page.Name));
            }

            context.Load(layout);

            // Create a publishing page
            PublishingPageInformation publishingPageInfo = new PublishingPageInformation();

            publishingPageInfo.Name = page.Name;
            publishingPageInfo.PageLayoutListItem = layout;

            Microsoft.SharePoint.Client.Publishing.PublishingPage publishingPage = webPub.AddPublishingPage(publishingPageInfo);

            //publishingPage.ListItem.File.Approve(string.Empty);

            context.Load(publishingPage);
            context.Load(publishingPage.ListItem.File, obj => obj.ServerRelativeUrl);
            context.ExecuteQuery();
        }
Exemple #5
0
        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 { }
            }
        }
        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);
        }
Exemple #7
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            PublishingWeb pWeb           = PublishingWeb.GetPublishingWeb(site.RootWeb);
            bool          pageNotCreated = !pWeb.GetPublishingPages().Cast <PublishingPage>().Any(p => p.Name == pageName);

            if (pageNotCreated)
            {
                //если такой страницы еще нет - создаем ее
                PublishingPage pPage = pWeb.GetPublishingPages().Add(pageName, null);

                pPage.CheckOut();

                using (Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager wpManager = site.RootWeb.GetLimitedWebPartManager(pPage.Url, PersonalizationScope.Shared))
                {
                    ResultScriptWebPart searchResults = GetImportedWebPart(site, wpName) as ResultScriptWebPart;
                    searchResults.Title      = wpTitle;
                    searchResults.ChromeType = PartChromeType.None;

                    wpManager.AddWebPart(searchResults, "Top", 0);
                }

                pPage.CheckIn(string.Empty);
            }
        }
        private void DeployDefinition(object modelHost, WebModelHost webModelHost, PageLayoutAndSiteTemplateSettingsDefinition definition)
        {
            var web           = webModelHost.HostWeb;
            var publishingWeb = PublishingWeb.GetPublishingWeb(web);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = web,
                ObjectType       = typeof(SPWeb),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });

            ProcessWebTemplateSettings(publishingWeb, definition);
            ProcessPageLayoutSettings(publishingWeb, definition);
            ProcessNewPageDefaultSettings(publishingWeb, definition);
            ProcessConverBlankSpacesIntoHyphenSetting(publishingWeb, definition);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = web,
                ObjectType       = typeof(SPWeb),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });

            publishingWeb.Update();
        }
Exemple #9
0
        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite siteCollection = properties.Feature.Parent as SPSite;

            if (siteCollection != null)
            {
                SPWeb  topLevelSite       = siteCollection.RootWeb;
                String WebAppRelativePath = topLevelSite.ServerRelativeUrl;
                if (!WebAppRelativePath.EndsWith("/"))
                {
                    WebAppRelativePath += "/";
                }
                foreach (SPWeb site in siteCollection.AllWebs)
                {
                    if (!site.WebTemplate.Contains("APP"))
                    {
                        var pubWeb = PublishingWeb.GetPublishingWeb(site);
                        var webNavigationSettings = new Microsoft.SharePoint.Publishing.Navigation.WebNavigationSettings(site);
                        webNavigationSettings.GlobalNavigation.Source  = Microsoft.SharePoint.Publishing.Navigation.StandardNavigationSource.PortalProvider;
                        webNavigationSettings.CurrentNavigation.Source = Microsoft.SharePoint.Publishing.Navigation.StandardNavigationSource.PortalProvider;
                        webNavigationSettings.Update();
                        pubWeb.Update();
                        site.MasterUrl       = WebAppRelativePath + "_catalogs/masterpage/seattle.master";
                        site.CustomMasterUrl = WebAppRelativePath + "_catalogs/masterpage/seattle.master";
                        site.SiteLogoUrl     = "";
                        site.Update();
                    }
                }
            }
        }
 private void CheckInAndPublishPage(ClientContext context, PublishingWeb webPub, string fileUrl)
 {
     //get the home page
     Microsoft.SharePoint.Client.File home = context.Web.GetFileByServerRelativeUrl(fileUrl);
     home.CheckIn(string.Empty, CheckinType.MajorCheckIn);
     home.Publish(string.Empty);
 }
        /// <summary>
        /// A site was provisioned.
        /// </summary>
        public override void WebProvisioned(SPWebEventProperties properties)
        {
            base.WebProvisioned(properties);
            SPSite siteCollection = properties.Web.Site;
            SPWeb  subSite        = properties.Web;

            if (!subSite.WebTemplate.Contains("APP"))
            {
                Guid sitePublishingGuid = new Guid("f6924d36-2fa8-4f0b-b16d-06b7250180fa");
                Guid webPublishingGuid  = new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb");

                EnsureSiteFeatureActivated(sitePublishingGuid, siteCollection);
                EnsureWebFeatureActivated(webPublishingGuid, siteCollection, subSite);

                var pubWeb = PublishingWeb.GetPublishingWeb(subSite);
                var webNavigationSettings = new Microsoft.SharePoint.Publishing.Navigation.WebNavigationSettings(subSite);
                webNavigationSettings.GlobalNavigation.Source  = Microsoft.SharePoint.Publishing.Navigation.StandardNavigationSource.InheritFromParentWeb;
                webNavigationSettings.CurrentNavigation.Source = Microsoft.SharePoint.Publishing.Navigation.StandardNavigationSource.PortalProvider;
                webNavigationSettings.Update();
                pubWeb.Update();

                subSite.MasterUrl       = siteCollection.RootWeb.MasterUrl;
                subSite.CustomMasterUrl = siteCollection.RootWeb.CustomMasterUrl;
                subSite.SiteLogoUrl     = siteCollection.RootWeb.SiteLogoUrl;
                subSite.Update();
            }
        }
        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);
                }
            }
        }
        // method for creating publising page
        private string CreatePublishingPage(string pageName, string pageLayoutName, bool isLandingPage)
        {
            string createdPageURL = string.Empty;

            // elevated privilages as not all user will have permission to create a new page
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                // get current web
                SPWeb oWeb                  = SPContext.Current.Web;
                string fullPageUrl          = string.Empty;
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(oWeb);
                /* Get the publishing web page collection list. */
                PublishingPageCollection publishingPageCollection = publishingWeb.GetPublishingPages();
                //GetPageLayoutName(application);
                if (!string.IsNullOrEmpty(pageLayoutName))
                {
                    /* Search for the page layout for creating the new page */
                    List <PageLayout> layouts = new List <PageLayout>(publishingWeb.GetAvailablePageLayouts());
                    PageLayout pageLayout     = layouts.Find(
                        delegate(PageLayout l)
                    {
                        return(l.Name.Equals(pageLayoutName, StringComparison.CurrentCultureIgnoreCase));
                    });
                    /*page layout exists*/
                    if (pageLayout != null)
                    {
                        PublishingPage newPage = null;
                        newPage       = publishingPageCollection.Add(pageName + ".aspx", pageLayout);
                        newPage.Title = pageName;
                        newPage.Update();

                        SPList li = newPage.ListItem.ParentList;

                        if (li.EnableModeration == false)
                        {
                            li.EnableModeration = true;
                            li.Update();
                        }
                        newPage.CheckIn("page checked in");
                        newPage.ListItem.File.Publish("page published");
                        newPage.ListItem.File.Approve("page approved");
                        /* Set newly created page as a welcome page */
                        if (isLandingPage == true)
                        {
                            fullPageUrl               = oWeb.Url + "/Pages/" + pageName + ".aspx";
                            SPFile fileNew            = publishingWeb.Web.GetFile(fullPageUrl);
                            publishingWeb.DefaultPage = fileNew;
                        }
                        publishingWeb.Update();

                        createdPageURL = newPage.Uri.AbsoluteUri.ToString();
                    }
                }
            });

            // return new page url
            return(createdPageURL);
        }
Exemple #14
0
        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();
                    }
                }
            }
        }
        /// <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);
            }
        }
        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;
            }
        }
        private void AddResultsForSPWeb(SPSite site, SPWeb web)
        {
            WBLogging.RecordsTypes.Verbose("In AddResultsForSPWeb(): looking at SPWeb: " + web.Url);


            try
            {
                PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);

                foreach (PublishingPage page in pubWeb.GetPublishingPages())
                {
                    WBLogging.RecordsTypes.Verbose("In AddResultsForSPWeb(): page = " + page.WBxToString());

                    if (page != null)
                    {
                        AddResultsForPublishingPage(page);

                        WBLogging.RecordsTypes.Verbose("InAddResultsForSPWeb() just finished for AddResultsForPublishingPage(): page = " + page.Name);
                    }
                }
            }
            catch (Exception e)
            {
                WBLogging.RecordsTypes.Verbose("In FindWhereRecordIsBeingUsed.AddResultsForSPWeb(): This SPWeb is probably not a publishing site: " + web.Url);

                StringBuilder command = new StringBuilder();
                command.Append("<script type=\"text/javascript\">errorProcessingPage(\"").Append(web.Url).Append("\", \"An exception occured at an SPWeb level: ").Append(e.Message).Append("\");</script>\n");
                command.Append("<!-- Full exception stack using ToString(): ");
                command.Append(e.ToString()).Append("-->\n\n");

                command.Append("<!-- Full exception stack using FlattenException(): ");
                command.Append(FlattenException(e)).Append("-->\n\n");

                Response.Write(command.ToString());
                Response.Flush();
            }

            WBLogging.RecordsTypes.Verbose("InAddResultsForSPWeb() about to look at sub webs for SPWeb: " + web.Url);

            foreach (SPWeb subWeb in web.Webs)
            {
                if (subWeb != null)
                {
                    WBLogging.RecordsTypes.Verbose("InAddResultsForSPWeb() for a sub SPWeb: " + subWeb.Url);

                    AddResultsForSPWeb(site, subWeb);

                    WBLogging.RecordsTypes.Verbose("InAddResultsForSPWeb() returned from AddResultsForSPWeb for:" + subWeb.Url);

                    subWeb.Dispose();
                }
                else
                {
                    WBLogging.RecordsTypes.Verbose("InAddResultsForSPWeb() subweb was null:");
                }
            }
        }
Exemple #18
0
        public string GetPagesListName(SPWebInstance web)
        {
            if (web == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "A SPWeb must be supplied as the first parameter.");
            }

            return(PublishingWeb.GetPagesListName(web.Web));
        }
Exemple #19
0
        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));
        }
Exemple #20
0
        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.");
            }
        }
Exemple #21
0
        public PublishingWebInstance(ObjectInstance prototype, PublishingWeb publishingWeb)
            : this(prototype)
        {
            if (publishingWeb == null)
            {
                throw new ArgumentNullException("publishingWeb");
            }

            m_publishingWeb = publishingWeb;
        }
    public static void CreatePublishingPage(ClientContext ctx, string pageName, string pageLayoutName)
    {
        var pubWeb   = PublishingWeb.GetPublishingWeb(ctx, ctx.Web);
        var pageInfo = new PublishingPageInformation();

        pageInfo.Name = pageName;
        pageInfo.PageLayoutListItem = GetPageLayout(ctx, pageLayoutName);
        var publishingPage = pubWeb.AddPublishingPage(pageInfo);

        ctx.ExecuteQuery();
    }
Exemple #23
0
        private static SPFile CreateNewWelcomePage(SPWeb currentWeb, PublishingWeb publishingWeb, SPFile defaultPage)
        {
            PageLayout     welcomeLayout = publishingWeb.GetAvailablePageLayouts(ContentTypeId.WelcomePage)[0];
            PublishingPage welcomePage   = publishingWeb.GetPublishingPages().Add(DefaultFileName, welcomeLayout);

            defaultPage = currentWeb.GetFile(welcomePage.Url);
            publishingWeb.DefaultPage = defaultPage;
            publishingWeb.Update();
            //defaultPage.MoveTo("default.aspx", true);
            return(defaultPage);
        }
Exemple #24
0
 public List <string> GetAllPagesInWeb(SPWeb web)
 {
     if (PublishingWeb.IsPublishingWeb(web))
     {
         return(GetAllPublishingPages(PublishingWeb.GetPublishingWeb(web)));
     }
     else
     {
         return(GetAllPagesFromRoot(web));
     }
 }
        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 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;
                }
            }
        }
 private static VariationLabel GetVariationLabel(PublishingWeb web)
 {
     foreach (VariationLabel label in (new PublishingSite(web.Web.Site)).GetVariationLabels(false))
     {
         string prefix = new Uri(label.TopWebUrl).AbsolutePath;
         if (web.Web.ServerRelativeUrl.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) &&
             (web.Web.ServerRelativeUrl.Length == prefix.Length || web.Web.ServerRelativeUrl[prefix.Length] == '/'))
         {
             return(label);
         }
     }
     return(null);
 }
Exemple #28
0
        public static bool GetConverBlankSpacesIntoHyphen(this PublishingWeb publishingWeb)
        {
            var web = publishingWeb.Web;

            var key = "__AllowSpacesInNewPageName";

            if (!web.AllProperties.ContainsKey(key))
            {
                return(false);
            }

            return(ConvertUtils.ToBool(web.AllProperties[key]).Value);
        }
        private static string ExportToXml(ISharePointCommandContext context, PublishingPageInfo pageInfo)
        {
            string pageXml = null;

            PublishingWeb  publishingWeb = PublishingWeb.GetPublishingWeb(context.Web);
            PublishingPage page          = publishingWeb.GetPublishingPage(pageInfo.ServerRelativeUrl);

            if (page != null)
            {
                pageXml = ExportPublishingPage(page, context.Web, context).ToString();
            }

            return(pageXml);
        }
        private void ProcessConverBlankSpacesIntoHyphenSetting(PublishingWeb publishingWeb, PageLayoutAndSiteTemplateSettingsDefinition definition)
        {
            var web = publishingWeb.Web;

            var key = "__AllowSpacesInNewPageName";
            var value = definition.ConverBlankSpacesIntoHyphen.HasValue
                ? definition.ConverBlankSpacesIntoHyphen.ToString()
                : false.ToString();

            if (!web.AllProperties.ContainsKey(key))
                web.AllProperties.Add(key, value);
            else
                web.AllProperties[key] = value;
        }
Exemple #31
0
        /// <summary>
        /// Creates the publishing page asynchronous.
        /// </summary>
        /// <param name="layoutRelativeUrl">The layout relative URL.</param>
        /// <param name="pageNameWithExtension">The page name with extension.</param>
        /// <returns></returns>
        public async Task <PublishingPage> CreatePublishingPageAsync(string layoutRelativeUrl, string pageNameWithExtension)
        {
            var layoutItem = await GetPageLayoutItemAsync(layoutRelativeUrl);

            var publishingWeb = PublishingWeb.GetPublishingWeb(_ctx, _web);
            var page          = publishingWeb.AddPublishingPage(new PublishingPageInformation
            {
                Name = pageNameWithExtension,
                PageLayoutListItem = layoutItem
            });
            await _ctx.ExecuteQueryAsync();

            return(page);
        }
        private void ProcessConverBlankSpacesIntoHyphenSetting(
            WebModelHost webModelHost,
            PublishingWeb publishingWeb,
            PageLayoutAndSiteTemplateSettingsDefinition definition,
            List<ListItem> pageLayouts)
        {
            var web = publishingWeb.Web;

            var key = "__AllowSpacesInNewPageName";
            var value = definition.ConverBlankSpacesIntoHyphen.HasValue
                ? definition.ConverBlankSpacesIntoHyphen.ToString()
                : false.ToString();

            SetPropertyBagValue(web, key, value);
        }
        public static void SwapPageLayout(PublishingWeb publishingWeb, PageLayout defaultPageLayout, SPContentType ctype)
        {
            string checkInComment = "WET4 Automatic Event Handler Page Layout Fix";
            //
            // Validate the input parameters.
            if (null == publishingWeb)
            {
                throw new System.ArgumentNullException("publishingWeb");
            }
            if (null == defaultPageLayout)
            {
                throw new System.ArgumentNullException("defaultPageLayout");
            }

            SPList list = publishingWeb.PagesList;
            if (list.ContentTypes[defaultPageLayout.AssociatedContentType.Name] == null)
            {
                list.ContentTypes.Add(ctype);
            }
            SPContentType ct = list.ContentTypes[defaultPageLayout.AssociatedContentType.Name];

            PublishingPageCollection publishingPages = publishingWeb.GetPublishingPages();
            foreach (PublishingPage publishingPage in publishingPages)
            {
                if (publishingPage.ListItem.File.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    publishingPage.CheckOut();
                }
                publishingPage.ListItem["ContentTypeId"] = ct.Id;

                switch (publishingPage.Url)
                {
                    default:
                        publishingPage.Layout = defaultPageLayout;
                        publishingPage.Title = publishingWeb.Title;
                        break;
                }
                publishingPage.Update();
                publishingPage.CheckIn(checkInComment);
            }
        }
        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);
                }
            }
        }
        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>
        /// Adds the nodes.
        /// </summary>
        /// <param name="pubWeb">The publishing web.</param>
        /// <param name="isGlobal">if set to <c>true</c> [is global].</param>
        /// <param name="existingNodes">The existing nodes.</param>
        /// <param name="newNodes">The new nodes.</param>
        private static void AddNodes(PublishingWeb pubWeb, bool isGlobal, SPNavigationNodeCollection existingNodes, XmlNodeList newNodes)
        {
            if (newNodes.Count == 0)
                return;

            for (int i = 0; i < newNodes.Count; i++)
            {
                XmlElement newNodeXml = (XmlElement)newNodes[i];
                string url = newNodeXml.SelectSingleNode("Url").InnerText;
                string title = newNodeXml.GetAttribute("Title");
                NodeTypes type = NodeTypes.None;
                if (newNodeXml.SelectSingleNode("NodeType") != null && !string.IsNullOrEmpty(newNodeXml.SelectSingleNode("NodeType").InnerText))
                    type = (NodeTypes)Enum.Parse(typeof(NodeTypes), newNodeXml.SelectSingleNode("NodeType").InnerText);

                bool isVisible = true;
                if (!string.IsNullOrEmpty(newNodeXml.GetAttribute("IsVisible")))
                    isVisible = bool.Parse(newNodeXml.GetAttribute("IsVisible"));

                if (type == NodeTypes.Area)
                {
                    // You can't just add an "Area" node (which represents a sub-site) to the current web if the
                    // url does not correspond with an actual sub-site (the code will appear to work but you won't
                    // see anything when you load the page).  So we need to check and see if the node actually
                    // points to a sub-site - if it does not then change it to "AuthoredLinkToWeb".
                    SPWeb web = null;
                    try
                    {
                        string name = url.Trim('/');
                        if (name.Length != 0 && name.IndexOf("/") > 0)
                        {
                            name = name.Substring(name.LastIndexOf('/') + 1);
                        }
                        try
                        {
                            // pubWeb.Web.Webs[] does not return null if the item doesn't exist - it simply throws an exception (I hate that!)
                            web = pubWeb.Web.Webs[name];
                        }
                        catch (ArgumentException)
                        {
                        }
                        if (web == null || !web.Exists || web.ServerRelativeUrl.ToLower() != url.ToLower())
                        {
                            // The url doesn't correspond with a sub-site for the current web so change the node type.
                            // This is most likely due to copying navigation elements from another site
                            type = NodeTypes.AuthoredLinkToWeb;
                        }
                        else if (web.Exists && web.ServerRelativeUrl.ToLower() == url.ToLower())
                        {
                            // We did find a matching sub-site so now we need to set the visibility
                            if (isVisible)
                                pubWeb.Navigation.IncludeInNavigation(isGlobal, web.ID);
                            else
                                pubWeb.Navigation.ExcludeFromNavigation(isGlobal, web.ID);
                        }
                    }
                    finally
                    {
                        if (web != null)
                            web.Dispose();
                    }

                }
                else if (type == NodeTypes.Page)
                {
                    // Adding links to pages has the same limitation as sub-sites (Area nodes) so we need to make
                    // sure it actually exists and if it doesn't then change the node type.
                    PublishingPage page = null;
                    try
                    {
                        // Note that GetPublishingPages()[] does not return null if the item doesn't exist - it simply throws an exception (I hate that!)
                        page = pubWeb.GetPublishingPages()[url];
                    }
                    catch (ArgumentException)
                    {
                    }
                    if (page == null)
                    {
                        // The url doesn't correspond with a page for the current web so change the node type.
                        // This is most likely due to copying navigation elements from another site
                        type = NodeTypes.AuthoredLinkToPage;
                        url = pubWeb.Web.Site.MakeFullUrl(url);
                    }
                    else
                    {
                        // We did find a matching page so now we need to set the visibility
                        if (isVisible)
                            pubWeb.Navigation.IncludeInNavigation(isGlobal, page.ListItem.UniqueId);
                        else
                            pubWeb.Navigation.ExcludeFromNavigation(isGlobal, page.ListItem.UniqueId);
                    }
                }

                // If it's not a sub-site or a page that's part of the current web and it's set to
                // not be visible then just move on to the next (there is no visibility setting for
                // nodes that are not of type Area or Page).
                if (!isVisible && type != NodeTypes.Area && type != NodeTypes.Page)
                    continue;

                // Finally, can add the node to the collection.
                SPNavigationNode node = SPNavigationSiteMapNode.CreateSPNavigationNode(
                    title, url, type, existingNodes);

                // Now we need to set all the other properties
                foreach (XmlElement property in newNodeXml.ChildNodes)
                {
                    // We've already set these so don't set them again.
                    if (property.Name == "Url" || property.Name == "Node" || property.Name == "NodeType")
                        continue;

                    // CreatedDate and LastModifiedDate need to be the correct type - all other properties are strings
                    if (property.Name == "CreatedDate" && !string.IsNullOrEmpty(property.InnerText))
                    {
                        node.Properties["CreatedDate"] = DateTime.Parse(property.InnerText);
                        continue;
                    }
                    if (property.Name == "LastModifiedDate" && !string.IsNullOrEmpty(property.InnerText))
                    {
                        node.Properties["LastModifiedDate"] = DateTime.Parse(property.InnerText);
                        continue;
                    }

                    node.Properties[property.Name] = property.InnerText;
                }
                // If we didn't have a CreatedDate or LastModifiedDate then set them to now.
                if (node.Properties["CreatedDate"] == null)
                    node.Properties["CreatedDate"] = DateTime.Now;
                if (node.Properties["LastModifiedDate"] == null)
                    node.Properties["LastModifiedDate"] = DateTime.Now;

                // Save our changes to the node.
                node.Update();
                node.MoveToLast(existingNodes); // Should already be at the end but I prefer to make sure :)

                XmlNodeList childNodes = newNodeXml.SelectNodes("Node");

                // If we have child nodes then make a recursive call passing in the current nodes Children property as the collection to add to.
                if (childNodes.Count > 0)
                    AddNodes(pubWeb, isGlobal, node.Children, childNodes);
            }
        }
        /// <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));
                }
            }
        }
        /// <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);
            }
        }
        private static void ProcessWebTemplateSettings(PublishingWeb publishingWeb, PageLayoutAndSiteTemplateSettingsDefinition definition)
        {
            var web = publishingWeb.Web;

            if (definition.InheritWebTemplates.HasValue && definition.InheritWebTemplates.Value)
                publishingWeb.InheritAvailableWebTemplates();
            else if (definition.UseAnyWebTemplate.HasValue && definition.UseAnyWebTemplate.Value)
            {
                publishingWeb.AllowAllWebTemplates(definition.ResetAllSubsitesToInheritWebTemplates.HasValue
                    ? definition.ResetAllSubsitesToInheritWebTemplates.Value
                    : false);
            }
            else if (definition.UseDefinedWebTemplates.HasValue && definition.UseDefinedWebTemplates.Value)
            {
                var currentLocaleId = (uint)web.CurrencyLocaleID;
                var webTemplates = new List<SPWebTemplate>();

                webTemplates.AddRange(web.Site.GetWebTemplates(currentLocaleId).OfType<SPWebTemplate>());
                webTemplates.AddRange(web.Site.GetCustomWebTemplates(currentLocaleId).OfType<SPWebTemplate>());

                var selectedWebTemplates = new Collection<SPWebTemplate>();

                foreach (var selectedWebTemplateName in definition.DefinedWebTemplates)
                {
                    var targetWebTemplate =
                        webTemplates.FirstOrDefault(t => t.Name.ToUpper() == selectedWebTemplateName.ToUpper());

                    if (targetWebTemplate != null)
                        selectedWebTemplates.Add(targetWebTemplate);
                }

                if (selectedWebTemplates.Any())
                {
                    publishingWeb.SetAvailableWebTemplates(selectedWebTemplates, 0,
                        definition.ResetAllSubsitesToInheritWebTemplates.HasValue
                            ? definition.ResetAllSubsitesToInheritWebTemplates.Value
                            : false);
                }
            }
        }
 /// <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 publishing web.</param>
 public static void FixPages(PublishingWeb publishingWeb)
 {
     FixPages(publishingWeb, null, null, null, null, false, false);
 }
        private static void ProcessWebTemplateSettings(
            WebModelHost webModelHost,
            PublishingWeb publishingWeb,
            PageLayoutAndSiteTemplateSettingsDefinition definition,
            List<ListItem> pageLayouts)
        {
            //var web = publishingWeb.Web;

            //if (definition.InheritWebTemplates.HasValue && definition.InheritWebTemplates.Value)
            //    publishingWeb.InheritAvailableWebTemplates();
            //else if (definition.UseAnyWebTemplate.HasValue && definition.UseAnyWebTemplate.Value)
            //{
            //    publishingWeb.AllowAllWebTemplates(definition.ResetAllSubsitesToInheritWebTemplates.HasValue
            //        ? definition.ResetAllSubsitesToInheritWebTemplates.Value
            //        : false);
            //}
            //else if (definition.UseDefinedWebTemplates.HasValue && definition.UseDefinedWebTemplates.Value)
            //{
            //    var currentLocaleId = (uint)web.CurrencyLocaleID;
            //    var webTemplates = new List<SPWebTemplate>();

            //    webTemplates.AddRange(web.Site.GetWebTemplates(currentLocaleId).OfType<SPWebTemplate>());
            //    webTemplates.AddRange(web.Site.GetCustomWebTemplates(currentLocaleId).OfType<SPWebTemplate>());

            //    var selectedWebTemplates = new Collection<SPWebTemplate>();

            //    foreach (var selectedWebTemplateName in definition.DefinedWebTemplates)
            //    {
            //        var targetWebTemplate =
            //            webTemplates.FirstOrDefault(t => t.Name.ToUpper() == selectedWebTemplateName.ToUpper());

            //        if (targetWebTemplate != null)
            //            selectedWebTemplates.Add(targetWebTemplate);
            //    }

            //    if (selectedWebTemplates.Any())
            //    {
            //        publishingWeb.SetAvailableWebTemplates(selectedWebTemplates, 0,
            //            definition.ResetAllSubsitesToInheritWebTemplates.HasValue
            //                ? definition.ResetAllSubsitesToInheritWebTemplates.Value
            //                : false);
            //    }
            //}
        }
        private static void ProcessPageLayoutSettings(
            WebModelHost webModelHost,
            PublishingWeb publishingWeb,
            PageLayoutAndSiteTemplateSettingsDefinition definition,
            List<ListItem> pageLayouts)
        {
            var rootWeb = webModelHost.HostSite.RootWeb;
            var web = publishingWeb.Web;
            var context = web.Context;

            if (definition.InheritPageLayouts.HasValue && definition.InheritPageLayouts.Value)
            {
                SetPropertyBagValue(web, "__PageLayouts", "__inherit");
            }
            else if (definition.UseAnyPageLayout.HasValue && definition.UseAnyPageLayout.Value)
            {
                SetPropertyBagValue(web, "__PageLayouts", "");
            }
            else if (definition.UseDefinedPageLayouts.HasValue && definition.UseDefinedPageLayouts.Value)
            {
                var selectedPageLayouts = new List<ListItem>();

                foreach (var selectedLayoutName in definition.DefinedPageLayouts)
                {
                    var targetLayout = pageLayouts.FirstOrDefault(t => t["FileLeafRef"].ToString().ToUpper() == selectedLayoutName.ToUpper());

                    if (targetLayout != null)
                        selectedPageLayouts.Add(targetLayout);
                }

                if (selectedPageLayouts.Any())
                {
                    var resultString = CreateLayoutsXmlString(selectedPageLayouts,rootWeb.ServerRelativeUrl);
                    SetPropertyBagValue(web, "__PageLayouts", resultString);
                }
            }
        }
        private static void ProcessNewPageDefaultSettings(
            WebModelHost webModelHost,
            PublishingWeb publishingWeb,
            PageLayoutAndSiteTemplateSettingsDefinition definition,
            List<ListItem> pageLayouts)
        {
            var web = publishingWeb.Web;
            var context = web.Context;

            if (definition.InheritDefaultPageLayout.HasValue && definition.InheritDefaultPageLayout.Value)
            {
                SetPropertyBagValue(web, "__DefaultPageLayout", "__inherit");
            }
            else if (definition.UseDefinedDefaultPageLayout.HasValue && definition.UseDefinedDefaultPageLayout.Value)
            {
                var selectedLayoutName = definition.DefinedDefaultPageLayout;
                var targetLayout = pageLayouts.FirstOrDefault(t => t["FileLeafRef"].ToString().ToUpper() == selectedLayoutName.ToUpper());

                if (targetLayout != null)
                {
                    var resultString = CreateLayoutXmlString(targetLayout, webModelHost.HostSite.RootWeb.ServerRelativeUrl);
                    SetPropertyBagValue(web, "__DefaultPageLayout", resultString);
                }
            }
        }
        /// <summary>
        /// Gets the navigation as XML.
        /// </summary>
        /// <param name="pubweb">The pubweb.</param>
        /// <param name="webNode">The web node.</param>
        internal static void GetNavigation(PublishingWeb pubweb, XmlElement webNode)
        {
            XmlDocument xmlDoc = webNode.OwnerDocument;
            XmlElement navNode = (XmlElement)webNode.AppendChild(xmlDoc.CreateElement("Navigation"));
            XmlElement globalNode = (XmlElement)navNode.AppendChild(xmlDoc.CreateElement("Global"));
            globalNode.SetAttribute("IncludeSubSites", pubweb.Navigation.GlobalIncludeSubSites.ToString());
            globalNode.SetAttribute("IncludePages", pubweb.Navigation.GlobalIncludePages.ToString());

            XmlElement currentNode = (XmlElement)navNode.AppendChild(xmlDoc.CreateElement("Current"));
            currentNode.SetAttribute("IncludeSubSites", pubweb.Navigation.CurrentIncludeSubSites.ToString());
            currentNode.SetAttribute("IncludePages", pubweb.Navigation.CurrentIncludePages.ToString());

            EnumerateCollection(pubweb, true, pubweb.Navigation.GlobalNavigationNodes, globalNode);
            EnumerateCollection(pubweb, false, pubweb.Navigation.CurrentNavigationNodes, currentNode);
        }
        private string GetPageLayout(PublishingWeb web, SPFile page)
        {
            PageLayout pageLayout = null;
            try
            {
                if (PageLayout != null)
                {
                    if (web == null)
                        pageLayout = PageLayout.Read();
                    else
                    {
                        pageLayout = PageLayout.Read(web);
                    }

                    if (page != null && pageLayout != null)
                    {
                        if (pageLayout.ListItem.Web.Site.ID != page.Web.Site.ID)
                        {
                            throw new SPException("The specified page layout and page are not in the same site collection.");
                        }
                    }
                }
                if (pageLayout == null)
                    return null;

                string pageLayoutValue = pageLayout.ListItem.Web.Site.MakeFullUrl(pageLayout.ServerRelativeUrl) + ", " + pageLayout.Title;
                return pageLayoutValue;
            }
            catch
            {
                if (web.IsRoot) throw;
                return GetPageLayout(web.ParentPublishingWeb, page);
            }
            finally
            {
                if (pageLayout != null)
                {
                    pageLayout.ListItem.Web.Dispose();
                    pageLayout.ListItem.Web.Site.Dispose();
                }
            }
        }