public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var clientSidePageContentsHelper = new ClientSidePageContentsHelper();

                var baseUrl = web.EnsureProperty(w => w.ServerRelativeUrl) + "/SitePages/";

                // Extract the Home Page
                web.EnsureProperties(w => w.RootFolder.WelcomePage, w => w.ServerRelativeUrl, w => w.Url);
                var homePageUrl = web.RootFolder.WelcomePage;

                // Get pages library
                List sitePagesLibrary = null;
                try
                {
                    ListCollection listCollection = web.Lists;
                    listCollection.EnsureProperties(coll => coll.Include(li => li.BaseTemplate, li => li.RootFolder));
                    sitePagesLibrary = listCollection.Where(p => p.BaseTemplate == (int)ListTemplateType.WebPageLibrary).FirstOrDefault();
                } catch
                {
                    // fall back in case of exception when the site has been incorrectly provisioned which can cause access issues on lists/libraries.
                    sitePagesLibrary = web.Lists.GetByTitle("Site Pages");
                    sitePagesLibrary.EnsureProperties(l => l.BaseTemplate, l => l.RootFolder);
                }
                if (sitePagesLibrary != null)
                {
                    var templateFolderName   = string.Empty;
                    var templateFolderString = sitePagesLibrary.GetPropertyBagValueString(TemplatesFolderGuid, null);
                    Guid.TryParse(templateFolderString, out Guid templateFolderGuid);
                    if (templateFolderGuid != Guid.Empty)
                    {
                        var templateFolder = ((ClientContext)sitePagesLibrary.Context).Web.GetFolderById(templateFolderGuid);
                        templateFolderName = templateFolder.EnsureProperty(f => f.Name);
                    }
                    CamlQuery query = new CamlQuery
                    {
                        ViewXml = CAMLQueryByExtension
                    };
                    var pages = sitePagesLibrary.GetItems(query);
                    web.Context.Load(pages);
                    web.Context.ExecuteQueryRetry();
                    if (pages.FirstOrDefault() != null)
                    {
                        var currentPageIndex = 1;
                        foreach (var page in pages)
                        {
                            string pageUrl  = null;
                            string pageName = "";
                            if (page.FieldValues.ContainsKey(FileRefField) && !String.IsNullOrEmpty(page[FileRefField].ToString()))
                            {
                                pageUrl  = page[FileRefField].ToString();
                                pageName = page[FileLeafRefField].ToString();
                            }
                            else
                            {
                                //skip page
                                continue;
                            }

                            var isTemplate = false;
                            // Is this page a template?
                            if (pageUrl.IndexOf($"/{templateFolderName}/", StringComparison.InvariantCultureIgnoreCase) > -1)
                            {
                                isTemplate = true;
                            }
                            // Is this page the web's home page?
                            bool isHomePage = false;
                            if (pageUrl.EndsWith(homePageUrl, StringComparison.InvariantCultureIgnoreCase))
                            {
                                isHomePage = true;
                            }

                            // Get the name of the page, including the folder name
                            pageName = Regex.Replace(pageUrl, baseUrl, "", RegexOptions.IgnoreCase);

                            if (creationInfo.IncludeAllClientSidePages || isHomePage)
                            {
                                // Is this a client side page?
                                if (FieldExistsAndUsed(page, ClientSideApplicationId) && page[ClientSideApplicationId].ToString().Equals(FeatureId_Web_ModernPage.ToString(), StringComparison.InvariantCultureIgnoreCase))
                                {
                                    WriteSubProgress("ClientSidePage", !string.IsNullOrWhiteSpace(pageName) ? pageName : pageUrl, currentPageIndex, pages.Count);
                                    // extract the page using the OOB logic
                                    clientSidePageContentsHelper.ExtractClientSidePage(web, template, creationInfo, scope, pageUrl, pageName, isHomePage, isTemplate);
                                }
                            }
                            currentPageIndex++;
                        }
                    }
                }


                /*
                 * // Extract the Home Page
                 * web.EnsureProperties(w => w.RootFolder, w => w.ServerRelativeUrl, w => w.Url);
                 * web.RootFolder.EnsureProperty(w => w.WelcomePage);
                 *
                 * var homePageUrl = web.RootFolder.WelcomePage;
                 * var homepageName = System.IO.Path.GetFileName(web.RootFolder.WelcomePage);
                 * if (string.IsNullOrEmpty(homepageName))
                 * {
                 *  homepageName = "Home.aspx";
                 * }
                 *
                 * // Extract the home page
                 * new ClientSidePageContentsHelper().ExtractClientSidePage(web, template, creationInfo, scope, homePageUrl, homepageName, true);
                 */
                // If a base template is specified then use that one to "cleanup" the generated template model
                if (creationInfo.BaseTemplate != null)
                {
                    template = CleanupEntities(template, creationInfo.BaseTemplate);
                }
            }
            return(template);
        }
示例#2
0
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var clientSidePageContentsHelper = new ClientSidePageContentsHelper();

                // Extract the Home Page
                web.EnsureProperties(w => w.RootFolder.WelcomePage, w => w.ServerRelativeUrl, w => w.Url);
                var homePageUrl = web.RootFolder.WelcomePage;

                // Get pages library
                List sitePagesLibrary = null;
                try
                {
                    ListCollection listCollection = web.Lists;
                    listCollection.EnsureProperties(coll => coll.Include(li => li.BaseTemplate, li => li.RootFolder));
                    sitePagesLibrary = listCollection.Where(p => p.BaseTemplate == (int)ListTemplateType.WebPageLibrary).FirstOrDefault();
                }
                catch
                {
                    // fall back in case of exception when the site has been incorrectly provisioned which can cause access issues on lists/libraries.
                    sitePagesLibrary = web.Lists.GetByTitle("Site Pages");
                    sitePagesLibrary.EnsureProperties(l => l.BaseTemplate, l => l.RootFolder);
                }

                if (sitePagesLibrary != null)
                {
                    var baseUrl = $"{sitePagesLibrary.RootFolder.ServerRelativeUrl}/";

                    var templateFolderName   = PnP.Framework.Pages.ClientSidePage.DefaultTemplatesFolder;// string.Empty;
                    var templateFolderString = sitePagesLibrary.GetPropertyBagValueString(TemplatesFolderGuid, null);
                    Guid.TryParse(templateFolderString, out Guid templateFolderGuid);
                    if (templateFolderGuid != Guid.Empty)
                    {
                        try
                        {
                            var templateFolder = ((ClientContext)sitePagesLibrary.Context).Web.GetFolderById(templateFolderGuid);
                            templateFolderName = templateFolder.EnsureProperty(f => f.Name);
                        }
                        catch
                        {
                            //eat it and continue with default name
                        }
                    }
                    CamlQuery query = new CamlQuery
                    {
                        ViewXml = CAMLQueryByExtension
                    };
                    var pages = sitePagesLibrary.GetItems(query);
                    web.Context.Load(pages);
                    web.Context.ExecuteQueryRetry();
                    if (pages.FirstOrDefault() != null)
                    {
                        // Prep a list of pages to export allowing us hanlde translations
                        List <PageToExport> pagesToExport = new List <PageToExport>();
                        foreach (var page in pages)
                        {
                            PageToExport pageToExport = new PageToExport()
                            {
                                ListItem            = page,
                                IsTranslation       = false,
                                TranslatedLanguages = null,
                            };

                            // If multi-lingual is enabled these fields will be available on the SitePages library
                            if (page.FieldValues.ContainsKey(SPIsTranslation) && page[SPIsTranslation] != null && !string.IsNullOrEmpty(page[SPIsTranslation].ToString()))
                            {
                                if (bool.TryParse(page[SPIsTranslation].ToString(), out bool isTranslation))
                                {
                                    pageToExport.IsTranslation = isTranslation;
                                }
                            }

                            if (page.FieldValues.ContainsKey(PageIDField) && page[PageIDField] != null && !string.IsNullOrEmpty(page[PageIDField].ToString()))
                            {
                                pageToExport.PageId = Guid.Parse(page[PageIDField].ToString());
                            }

                            if (page.FieldValues.ContainsKey(SPTranslationSourceItemId) && page[SPTranslationSourceItemId] != null && !string.IsNullOrEmpty(page[SPTranslationSourceItemId].ToString()))
                            {
                                pageToExport.SourcePageId = Guid.Parse(page[SPTranslationSourceItemId].ToString());
                            }

                            if (page.FieldValues.ContainsKey(SPTranslationLanguage) && page[SPTranslationLanguage] != null && !string.IsNullOrEmpty(page[SPTranslationLanguage].ToString()))
                            {
                                pageToExport.Language = page[SPTranslationLanguage].ToString();
                            }

                            if (page.FieldValues.ContainsKey(SPTranslatedLanguages) && page[SPTranslatedLanguages] != null && !string.IsNullOrEmpty(page[SPTranslatedLanguages].ToString()))
                            {
                                pageToExport.TranslatedLanguages = new List <string>(page[SPTranslatedLanguages] as string[]);
                            }

                            string pageUrl  = null;
                            string pageName = "";
                            if (page.FieldValues.ContainsKey(FileRefField) && !String.IsNullOrEmpty(page[FileRefField].ToString()))
                            {
                                pageUrl  = page[FileRefField].ToString();
                                pageName = page[FileLeafRefField].ToString();
                            }
                            else
                            {
                                //skip page
                                continue;
                            }

                            var isTemplate = false;
                            // Is this page a template?
                            if (pageUrl.IndexOf($"/{templateFolderName}/", StringComparison.InvariantCultureIgnoreCase) > -1)
                            {
                                isTemplate = true;
                            }
                            // Is this page the web's home page?
                            bool isHomePage = false;
                            if (pageUrl.EndsWith(homePageUrl, StringComparison.InvariantCultureIgnoreCase))
                            {
                                isHomePage = true;
                            }

                            // Get the name of the page, including the folder name
                            pageName = Regex.Replace(pageUrl, baseUrl, "", RegexOptions.IgnoreCase);

                            pageToExport.IsHomePage = isHomePage;
                            pageToExport.IsTemplate = isTemplate;
                            pageToExport.PageName   = pageName;
                            pageToExport.PageUrl    = pageUrl;
                            pagesToExport.Add(pageToExport);
                        }

                        // Populate SourcePageName to make it easier to hookup translations at export time
                        foreach (var page in pagesToExport.Where(p => p.IsTranslation))
                        {
                            var sourcePage = pagesToExport.Where(p => p.PageId == page.SourcePageId).FirstOrDefault();
                            if (sourcePage != null)
                            {
                                page.SourcePageName = sourcePage.PageName;
                            }
                        }

                        var currentPageIndex = 1;
                        foreach (var page in pagesToExport.OrderBy(p => p.IsTranslation))
                        {
                            if (creationInfo.IncludeAllClientSidePages || page.IsHomePage)
                            {
                                // Is this a client side page?
                                if (FieldExistsAndUsed(page.ListItem, ClientSideApplicationId) && page.ListItem[ClientSideApplicationId].ToString().Equals(FeatureId_Web_ModernPage.ToString(), StringComparison.InvariantCultureIgnoreCase))
                                {
                                    WriteSubProgress("ClientSidePage", !string.IsNullOrWhiteSpace(page.PageName) ? page.PageName : page.PageUrl, currentPageIndex, pages.Count);
                                    // extract the page using the OOB logic
                                    clientSidePageContentsHelper.ExtractClientSidePage(web, template, creationInfo, scope, page);
                                }
                            }
                            currentPageIndex++;
                        }
                    }
                }

                // If a base template is specified then use that one to "cleanup" the generated template model
                if (creationInfo.BaseTemplate != null)
                {
                    template = CleanupEntities(template, creationInfo.BaseTemplate);
                }
            }
            return(template);
        }
        public ProvisioningTemplate Extract(ClientContext ctx, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInformation, PnPMonitoredScope scope, string configurationData)
        {
            var web = ctx.Web;

            #region Extract all client side pages
            var clientSidePageContentsHelper = new ClientSidePageContentsHelper();

            // Extract the Home Page
            web.EnsureProperties(w => w.RootFolder.WelcomePage, w => w.ServerRelativeUrl, w => w.Url);
            var homePageUrl = web.RootFolder.WelcomePage;

            // Get pages library
            ListCollection listCollection = web.Lists;
            listCollection.EnsureProperties(coll => coll.Include(li => li.BaseTemplate, li => li.RootFolder));
            var sitePagesLibrary = listCollection.Where(p => p.BaseTemplate == (int)ListTemplateType.WebPageLibrary).FirstOrDefault();
            if (sitePagesLibrary != null)
            {
                CamlQuery query = new CamlQuery
                {
                    ViewXml = CAMLQueryByExtension
                };
                var pages = sitePagesLibrary.GetItems(query);
                web.Context.Load(pages);
                web.Context.ExecuteQueryRetry();
                if (pages.FirstOrDefault() != null)
                {
                    foreach (var page in pages)
                    {
                        string pageUrl  = null;
                        string pageName = "";
                        if (page.FieldValues.ContainsKey(FileRefField) && !String.IsNullOrEmpty(page[FileRefField].ToString()))
                        {
                            pageUrl  = page[FileRefField].ToString();
                            pageName = page[FileLeafRefField].ToString();
                        }
                        else
                        {
                            //skip page
                            continue;
                        }

                        // Is this page the web's home page?
                        bool isHomePage = false;
                        if (pageUrl.EndsWith(homePageUrl, StringComparison.InvariantCultureIgnoreCase))
                        {
                            isHomePage = true;
                        }

                        // Is this a client side page?
                        if (FieldExistsAndUsed(page, ClientSideApplicationId) && page[ClientSideApplicationId].ToString().Equals(FeatureId_Web_ModernPage.ToString(), StringComparison.InvariantCultureIgnoreCase))
                        {
                            // extract the page using the OOB logic
                            clientSidePageContentsHelper.ExtractClientSidePage(web, template, creationInformation, scope, pageUrl, pageName, isHomePage);
                        }
                    }
                }
            }
            #endregion

            #region Cleanup template
            // Mark all pages as overwrite
            foreach (var page in template.ClientSidePages)
            {
                page.Overwrite = true;
            }

            // Drop all lists except FaqList and Site Assets
            foreach (var list in template.Lists.ToList())
            {
                if (!(list.Url.Equals("Lists/FAQList", StringComparison.CurrentCultureIgnoreCase) || list.Url.Equals("SiteAssets", StringComparison.CurrentCultureIgnoreCase)))
                {
                    template.Lists.Remove(list);
                }
            }

            // Mark all files to be published in target
            foreach (var file in template.Files)
            {
                file.Level = OfficeDevPnP.Core.Framework.Provisioning.Model.FileLevel.Published;
            }

            // Export the FAQ list items
            try
            {
                var faqTemplateList = template.Lists.Where(p => p.Url.Equals("Lists/FAQList", StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                if (faqTemplateList != null)
                {
                    var faqList = web.GetListByUrl("Lists/FAQList");
                    ListItemCollection faqListItems = faqList.GetItems(CamlQuery.CreateAllItemsQuery());
                    web.Context.Load(faqListItems, f => f.Include(item => item["Title"],
                                                                  item => item["Product"],
                                                                  item => item["Section_x0020_Header"],
                                                                  item => item["Answer"],
                                                                  item => item["Visible"],
                                                                  item => item["SortOrder"]));
                    web.Context.ExecuteQueryRetry();
                    foreach (ListItem faq in faqListItems)
                    {
                        var faqValues = new Dictionary <string, string>();
                        faqValues.Add("Title", FieldExistsAndUsed(faq, "Title") ? faq["Title"].ToString() : "");
                        faqValues.Add("Product", FieldExistsAndUsed(faq, "Product") ? faq["Product"].ToString() : "");
                        faqValues.Add("Section_x0020_Header", FieldExistsAndUsed(faq, "Section_x0020_Header") ? faq["Section_x0020_Header"].ToString() : "");
                        faqValues.Add("Answer", FieldExistsAndUsed(faq, "Answer") ? TokenizeField(web, faq["Answer"].ToString()) : "");
                        faqValues.Add("Visible", FieldExistsAndUsed(faq, "Visible") ? faq["Visible"].ToString() : "");
                        faqValues.Add("SortOrder", FieldExistsAndUsed(faq, "SortOrder") ? faq["SortOrder"].ToString() : "");
                        faqTemplateList.DataRows.Add(new DataRow(faqValues, faq["Title"].ToString()));
                    }

                    // Configure data rows
                    faqTemplateList.DataRows.KeyColumn      = "Title";
                    faqTemplateList.DataRows.UpdateBehavior = UpdateBehavior.Overwrite;
                }
            }
            catch (Exception ex)
            {
                scope.LogError("Something went wrong with the extraction of the list items. Error {0}", ex.Message);
            }
            #endregion

            return(template);
        }