private SubSite ParseSubsiteSequences(Web subweb, ref ProvisioningHierarchy tenantTemplate, ExtractConfiguration configuration, int currentDepth, int maxDepth)
        {
            subweb.EnsureProperties(sw => sw.Url, sw => sw.Title, sw => sw.QuickLaunchEnabled, sw => sw.Description, sw => sw.Language, sw => sw.RegionalSettings.TimeZone, sw => sw.Webs, sw => sw.HasUniqueRoleAssignments);

            var subwebTemplate = subweb.GetProvisioningTemplate(configuration.ToCreationInformation(subweb));
            var uniqueid       = subweb.Id.ToString("N");

            subwebTemplate.Id = $"TEMPLATE-{uniqueid}";

            tenantTemplate.Templates.Add(subwebTemplate);

            tenantTemplate.Parameters.Add($"SUBSITE_{uniqueid}_URL", subweb.Url.Substring(subweb.Url.LastIndexOf("/")));
            tenantTemplate.Parameters.Add($"SUBSITE_{uniqueid}_TITLE", subweb.Title);
            var subSiteCollection = new TeamNoGroupSubSite()
            {
                Url   = $"{{parameter:SUBSITE_{uniqueid}_URL}}",
                Title = $"{{parameter:SUBSITE_{uniqueid}_TITLE}}",
                QuickLaunchEnabled             = subweb.QuickLaunchEnabled,
                Description                    = subweb.Description,
                Language                       = (int)subweb.Language,
                TimeZoneId                     = subweb.RegionalSettings.TimeZone.Id,
                UseSamePermissionsAsParentSite = !subweb.HasUniqueRoleAssignments,
                Templates                      = { subwebTemplate.Id }
            };
            bool traverse = true;

            if (maxDepth != 0)
            {
                currentDepth++;
                traverse = currentDepth <= maxDepth;
            }
            if (traverse && subweb.Webs.AreItemsAvailable)
            {
                currentDepth++;
                foreach (var subsubweb in subweb.Webs)
                {
                    subSiteCollection.Sites.Add(ParseSubsiteSequences(subsubweb, ref tenantTemplate, configuration, currentDepth, maxDepth));
                }
            }
            return(subSiteCollection);
        }
        private void ExtractTemplate(string dirName, string fileName, ExtractConfiguration configuration)
        {
            var outputTemplate = new ProvisioningTemplate();

            outputTemplate.Id = Guid.NewGuid().ToString("N");
            var helper = new OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.Utilities.ClientSidePageContentsHelper();
            ProvisioningTemplateCreationInformation ci = null;

            if (configuration != null)
            {
                ci = configuration.ToCreationInformation(SelectedWeb);
            }
            else
            {
                ci = new ProvisioningTemplateCreationInformation(SelectedWeb);
            }
            if (MyInvocation.BoundParameters.ContainsKey(nameof(PersistBrandingFiles)))
            {
                ci.PersistBrandingFiles = PersistBrandingFiles;
            }
            if (!string.IsNullOrEmpty(dirName))
            {
                var fileSystemConnector = new FileSystemConnector(dirName, "");
                ci.FileConnector = fileSystemConnector;
            }
            helper.ExtractClientSidePage(SelectedWeb, outputTemplate, ci, new OfficeDevPnP.Core.Diagnostics.PnPMonitoredScope(), null, Identity.Name, false);

            if (!string.IsNullOrEmpty(fileName))
            {
                System.IO.File.WriteAllText(Path.Combine(dirName, fileName), outputTemplate.ToXML());
            }
            else
            {
                WriteObject(outputTemplate.ToXML());
            }
        }
Esempio n. 3
0
        private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName, ExtractConfiguration configuration)
        {
            CurrentWeb.EnsureProperty(w => w.Url);
            ProvisioningTemplateCreationInformation creationInformation = null;

            if (configuration != null)
            {
                creationInformation = configuration.ToCreationInformation(CurrentWeb);
            }
            else
            {
                creationInformation = new ProvisioningTemplateCreationInformation(CurrentWeb);
            }

            if (ParameterSpecified(nameof(Handlers)))
            {
                creationInformation.HandlersToProcess = Handlers;
            }
            if (ParameterSpecified(nameof(ExcludeHandlers)))
            {
                foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers)))
                {
                    if (!ExcludeHandlers.Has(handler) && handler != Handlers.All)
                    {
                        Handlers = Handlers | handler;
                    }
                }
                creationInformation.HandlersToProcess = Handlers;
            }

            var extension = "";

            if (packageName != null)
            {
                if (packageName.IndexOf(".", StringComparison.Ordinal) > -1)
                {
                    extension = packageName.Substring(packageName.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
                }
                else
                {
                    packageName += ".pnp";
                    extension    = ".pnp";
                }
            }

            var fileSystemConnector = new FileSystemConnector(path, "");

            if (extension == ".pnp")
            {
                creationInformation.FileConnector = new OpenXMLConnector(packageName, fileSystemConnector);
            }
            else if (extension == ".md")
            {
                creationInformation.FileConnector = fileSystemConnector;
            }
            else
            {
                creationInformation.FileConnector = fileSystemConnector;
            }
#pragma warning disable 618
            if (ParameterSpecified(nameof(PersistBrandingFiles)))
            {
                creationInformation.PersistBrandingFiles = PersistBrandingFiles;
            }
#pragma warning restore 618
            creationInformation.PersistPublishingFiles       = PersistPublishingFiles;
            creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles;
            if (ParameterSpecified(nameof(IncludeSiteGroups)))
            {
                creationInformation.IncludeSiteGroups = IncludeSiteGroups;
            }
            creationInformation.IncludeTermGroupsSecurity  = IncludeTermGroupsSecurity;
            creationInformation.IncludeSearchConfiguration = IncludeSearchConfiguration;
            if (ParameterSpecified(nameof(IncludeHiddenLists)))
            {
                creationInformation.IncludeHiddenLists = IncludeHiddenLists;
            }
            if (ParameterSpecified(nameof(IncludeAllPages)))
            {
                creationInformation.IncludeAllClientSidePages = IncludeAllPages;
            }
            creationInformation.SkipVersionCheck = SkipVersionCheck;
            if (ParameterSpecified(nameof(ContentTypeGroups)) && ContentTypeGroups != null)
            {
                creationInformation.ContentTypeGroupsToInclude = ContentTypeGroups.ToList();
            }
            creationInformation.PersistMultiLanguageResources = PersistMultiLanguageResources;
            if (extension == ".pnp")
            {
                // if file is of pnp format, persist all files
                creationInformation.PersistBrandingFiles          = true;
                creationInformation.PersistPublishingFiles        = true;
                creationInformation.PersistMultiLanguageResources = true;
            }
            if (!string.IsNullOrEmpty(ResourceFilePrefix))
            {
                creationInformation.ResourceFilePrefix = ResourceFilePrefix;
            }
            else
            {
                if (Out != null)
                {
                    FileInfo fileInfo = new FileInfo(Out);
                    var      prefix   = fileInfo.Name;
                    // strip extension, if there is any
                    var indexOfLastDot = prefix.LastIndexOf(".", StringComparison.Ordinal);
                    if (indexOfLastDot > -1)
                    {
                        prefix = prefix.Substring(0, indexOfLastDot);
                    }
                    creationInformation.ResourceFilePrefix = prefix;
                }
            }
            if (ExtensibilityHandlers != null)
            {
                creationInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList();
            }

#pragma warning disable CS0618 // Type or member is obsolete
            if (NoBaseTemplate)
            {
                creationInformation.BaseTemplate = null;
            }
            else
            {
                creationInformation.BaseTemplate = CurrentWeb.GetBaseTemplate();
            }
#pragma warning restore CS0618 // Type or member is obsolete

            creationInformation.ProgressDelegate = (message, step, total) =>
            {
                var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));

                WriteProgress(new ProgressRecord(0, $"Extracting Template from {CurrentWeb.Url}", message)
                {
                    PercentComplete = percentage
                });
                WriteProgress(new ProgressRecord(1, " ", " ")
                {
                    RecordType = ProgressRecordType.Completed
                });
            };
            creationInformation.MessagesDelegate = (message, type) =>
            {
                switch (type)
                {
                case ProvisioningMessageType.Warning:
                {
                    WriteWarning(message);
                    break;
                }

                case ProvisioningMessageType.Progress:
                {
                    var activity = message;
                    if (message.IndexOf("|") > -1)
                    {
                        var messageSplitted = message.Split('|');
                        if (messageSplitted.Length == 4)
                        {
                            var current = double.Parse(messageSplitted[2]);
                            var total   = double.Parse(messageSplitted[3]);
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.Activity          = messageSplitted[0];
                            subProgressRecord.StatusDescription = messageSplitted[1];
                            subProgressRecord.PercentComplete   = Convert.ToInt32((100 / total) * current);
                            WriteProgress(subProgressRecord);
                        }
                        else
                        {
                            subProgressRecord.Activity          = "Processing";
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.StatusDescription = activity;
                            subProgressRecord.PercentComplete   = 0;
                            WriteProgress(subProgressRecord);
                        }
                    }
                    else
                    {
                        subProgressRecord.Activity          = "Processing";
                        subProgressRecord.RecordType        = ProgressRecordType.Processing;
                        subProgressRecord.StatusDescription = activity;
                        subProgressRecord.PercentComplete   = 0;
                        WriteProgress(subProgressRecord);
                    }
                    break;
                }

                case ProvisioningMessageType.Completed:
                {
                    WriteProgress(new ProgressRecord(1, message, " ")
                        {
                            RecordType = ProgressRecordType.Completed
                        });
                    break;
                }
                }
            };

            if (IncludeAllTermGroups)
            {
                creationInformation.IncludeAllTermGroups = true;
            }
            else
            {
                if (IncludeSiteCollectionTermGroup)
                {
                    creationInformation.IncludeSiteCollectionTermGroup = true;
                }
            }

            if (ParameterSpecified(nameof(ExcludeContentTypesFromSyndication)))
            {
                creationInformation.IncludeContentTypesFromSyndication = !ExcludeContentTypesFromSyndication.ToBool();
            }

            if (ListsToExtract != null && ListsToExtract.Count > 0)
            {
                creationInformation.ListsToExtract.AddRange(ListsToExtract);
            }
            ProvisioningTemplate template = null;
            using (var provisioningContext = new PnPProvisioningContext(async(resource, scope) =>
            {
                return(await TokenRetrieval.GetAccessTokenAsync(resource, scope));
                // if (resource.ToLower().StartsWith("https://"))
                // {
                //     var uri = new Uri(resource);
                //     resource = uri.Authority;
                // }
                // if (resource.ToLower().Contains(".sharepoint."))
                // {
                //     // SharePoint
                //     var authManager = PnPConnection.CurrentConnection.Context.GetContextSettings().AuthenticationManager;
                //     if (authManager != null)
                //     {
                //         var token = await authManager.GetAccessTokenAsync($"https://{resource}");
                //         if (token != null)
                //         {
                //             return token;
                //         }
                //     }
                // }

                // // Get Azure AD Token
                // if (PnPConnection.CurrentConnection != null)
                // {
                //     var graphAccessToken = await PnPConnection.CurrentConnection.TryGetAccessTokenAsync(Enums.TokenAudience.MicrosoftGraph);
                //     if (graphAccessToken != null)
                //     {
                //         // Authenticated using -Graph or using another way to retrieve the accesstoken with Connect-PnPOnline
                //         return graphAccessToken;
                //     }
                // }

                // if (PnPConnection.CurrentConnection.PSCredential != null)
                // {
                //     // Using normal credentials
                //     return await TokenHandler.AcquireTokenAsync(resource, null);
                // }
                // else
                // {
                //     // No token...
                //     if (resource.ToLower().Contains(".sharepoint."))
                //     {
                //         return null;
                //     }
                //     else
                //     {
                //         throw new PSInvalidOperationException($"Your template contains artifacts that require an access token for {resource}. Either connect with a clientid which the appropriate permissions, or use credentials with Connect-PnPOnline after providing consent to the PnP Management Shell application first by executing: Register-PnPManagementShellAccess. See https://pnp.github.io/powershell/articles/authentication.html");
                //     }
                // }
            }))
            {
                template = CurrentWeb.GetProvisioningTemplate(creationInformation);
            }
            // Set metadata for template, if any
            SetTemplateMetadata(template, TemplateDisplayName, TemplateImagePreviewUrl, TemplateProperties);

            if (!OutputInstance)
            {
                var formatter = ProvisioningHelper.GetFormatter(schema);

                if (extension == ".pnp")
                {
                    XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                        creationInformation.FileConnector as OpenXMLConnector);
                    var templateFileName = packageName.Substring(0, packageName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                    provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
                }
                else if (extension == ".md")
                {
                    WriteWarning("The generation of a markdown report is work in progress, it will improve/grow with later releases.");
                    ITemplateFormatter mdFormatter = new MarkdownPnPFormatter();
                    using (var outputStream = mdFormatter.ToFormattedTemplate(template))
                    {
                        using (var fileStream = File.Create(Path.Combine(path, packageName)))
                        {
                            outputStream.Seek(0, SeekOrigin.Begin);
                            outputStream.CopyTo(fileStream);
                            fileStream.Close();
                        }
                    }
                }
                else
                {
                    if (Out != null)
                    {
                        XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(path, "");
                        provider.SaveAs(template, Path.Combine(path, packageName), formatter, TemplateProviderExtensions);
                    }
                    else
                    {
                        var outputStream = formatter.ToFormattedTemplate(template);
                        var reader       = new StreamReader(outputStream);

                        WriteObject(reader.ReadToEnd());
                    }
                }
            }
            else
            {
                WriteObject(template);
            }
        }
        public override ProvisioningHierarchy ExtractObjects(Tenant tenant, ProvisioningHierarchy hierarchy, ExtractConfiguration configuration)
        {
            ProvisioningHierarchy tenantTemplate     = new ProvisioningHierarchy();
            List <string>         siteCollectionUrls = configuration.Tenant.Sequence.SiteUrls;

            List <string> connectedSiteUrls = new List <string>();

            foreach (var siteCollectionUrl in siteCollectionUrls)
            {
                using (var siteContext = tenant.Context.Clone(siteCollectionUrl))
                {
                    if (configuration.Tenant.Sequence.IncludeJoinedSites && siteContext.Site.EnsureProperty(s => s.IsHubSite))
                    {
                        foreach (var hubsiteChildUrl in tenant.GetHubSiteChildUrls(siteContext.Site.EnsureProperty(s => s.Id)))
                        {
                            if (!connectedSiteUrls.Contains(hubsiteChildUrl) && !siteCollectionUrl.Contains(hubsiteChildUrl))
                            {
                                connectedSiteUrls.Add(hubsiteChildUrl);
                            }
                        }
                    }
                }
            }
            siteCollectionUrls.AddRange(connectedSiteUrls);

            ProvisioningSequence provisioningSequence = new ProvisioningSequence();

            provisioningSequence.ID = "TENANTSEQUENCE";
            foreach (var siteCollectionUrl in siteCollectionUrls)
            {
                var siteProperties = tenant.GetSitePropertiesByUrl(siteCollectionUrl, true);

                tenant.Context.Load(siteProperties);
                tenant.Context.ExecuteQueryRetry();
                Model.SiteCollection siteCollection = null;
                using (var siteContext = tenant.Context.Clone(siteCollectionUrl))
                {
                    siteContext.Site.EnsureProperties(s => s.Id, s => s.ShareByEmailEnabled);
                    var templateGuid = siteContext.Site.Id.ToString("N");
                    switch (siteProperties.Template)
                    {
                    case "SITEPAGEPUBLISHING#0":
                    {
                        siteCollection = new CommunicationSiteCollection();

                        siteCollection.IsHubSite = siteProperties.IsHubSite;
                        if (siteProperties.IsHubSite)
                        {
                            var hubsiteProperties = tenant.GetHubSitePropertiesByUrl(siteCollectionUrl);
                            tenant.Context.Load(hubsiteProperties);
                            tenant.Context.ExecuteQueryRetry();
                            siteCollection.HubSiteLogoUrl = hubsiteProperties.LogoUrl;
                            siteCollection.HubSiteTitle   = hubsiteProperties.Title;
                        }
                        siteCollection.Description = siteProperties.Description;
                        ((CommunicationSiteCollection)siteCollection).Language = (int)siteProperties.Lcid;
                        ((CommunicationSiteCollection)siteCollection).Owner    = siteProperties.OwnerEmail;
                        ((CommunicationSiteCollection)siteCollection).AllowFileSharingForGuestUsers = siteContext.Site.ShareByEmailEnabled;
                        tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_URL", siteProperties.Url);
                        ((CommunicationSiteCollection)siteCollection).Url = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_URL}}";
                        tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE", siteProperties.Title);
                        siteCollection.Title = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE}}";
                        break;
                    }

                    case "GROUP#0":
                    {
                        siteCollection           = new TeamSiteCollection();
                        siteCollection.IsHubSite = siteProperties.IsHubSite;
                        if (siteProperties.IsHubSite)
                        {
                            var hubsiteProperties = tenant.GetHubSitePropertiesByUrl(siteCollectionUrl);
                            tenant.Context.Load(hubsiteProperties);
                            tenant.Context.ExecuteQueryRetry();
                            siteCollection.HubSiteLogoUrl = hubsiteProperties.LogoUrl;
                            siteCollection.HubSiteTitle   = hubsiteProperties.Title;
                        }
                        siteCollection.Description = siteProperties.Description;

                        tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_ALIAS", siteProperties.Url.Substring(siteProperties.Url.LastIndexOf("/")));
                        ((TeamSiteCollection)siteCollection).Alias       = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_ALIAS}}";
                        ((TeamSiteCollection)siteCollection).DisplayName = siteProperties.Title;
                        ((TeamSiteCollection)siteCollection).HideTeamify = Core.Sites.SiteCollection.IsTeamifyPromptHiddenAsync(siteContext).GetAwaiter().GetResult();

                        tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE", siteProperties.Title);
                        siteCollection.Title = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE}}";
                        break;
                    }

                    case "STS#3":
                    {
                        siteCollection           = new TeamNoGroupSiteCollection();
                        siteCollection.IsHubSite = siteProperties.IsHubSite;
                        if (siteProperties.IsHubSite)
                        {
                            var hubsiteProperties = tenant.GetHubSitePropertiesByUrl(siteCollectionUrl);
                            tenant.Context.Load(hubsiteProperties);
                            tenant.Context.ExecuteQueryRetry();
                            siteCollection.HubSiteLogoUrl = hubsiteProperties.LogoUrl;
                            siteCollection.HubSiteTitle   = hubsiteProperties.Title;
                        }
                        siteCollection.Description = siteProperties.Description;
                        ((TeamNoGroupSiteCollection)siteCollection).Language   = (int)siteProperties.Lcid;
                        ((TeamNoGroupSiteCollection)siteCollection).Owner      = siteProperties.OwnerEmail;
                        ((TeamNoGroupSiteCollection)siteCollection).TimeZoneId = siteProperties.TimeZoneId;
                        tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_URL", siteProperties.Url);
                        ((TeamNoGroupSiteCollection)siteCollection).Url = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_URL}}";
                        tenantTemplate.Parameters.Add($"SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE", siteProperties.Title);
                        siteCollection.Title = $"{{parameter:SITECOLLECTION_{siteContext.Site.Id.ToString("N")}_TITLE}}";
                        break;
                    }
                    }
                    var siteTemplateCreationInfo = new ProvisioningTemplateCreationInformation(siteContext.Web);

                    // Retrieve the template for the site
                    if (configuration != null)
                    {
                        siteTemplateCreationInfo = configuration.ToCreationInformation(siteContext.Web);
                    }
                    var siteTemplate = siteContext.Web.GetProvisioningTemplate(siteTemplateCreationInfo);
                    siteTemplate.Id = $"TEMPLATE-{templateGuid}";
                    if (siteProperties.HubSiteId != null && siteProperties.HubSiteId != Guid.Empty && siteProperties.HubSiteId != siteContext.Site.Id && siteTemplate.WebSettings != null)
                    {
                        siteTemplate.WebSettings.HubSiteUrl = $"{{parameter:SITECOLLECTION_{siteProperties.HubSiteId.ToString("N")}_URL}}";
                    }
                    tenantTemplate.Templates.Add(siteTemplate);

                    siteCollection.Templates.Add(siteTemplate.Id);

                    if (siteProperties.WebsCount > 1 && configuration.Tenant.Sequence.IncludeSubsites)
                    {
                        var webs         = siteContext.Web.EnsureProperty(w => w.Webs);
                        int currentDepth = 1;
                        foreach (var subweb in webs)
                        {
                            siteCollection.Sites.Add(ParseSubsiteSequences(subweb, ref tenantTemplate, configuration, currentDepth, configuration.Tenant.Sequence.MaxSubsiteDepth));
                        }
                    }
                    provisioningSequence.SiteCollections.Add(siteCollection);
                }
            }

            tenantTemplate.Sequences.Add(provisioningSequence);

            PnPProvisioningContext.Current.ParsedSiteUrls.Clear();
            PnPProvisioningContext.Current.ParsedSiteUrls.AddRange(siteCollectionUrls);

            return(tenantTemplate);
        }
Esempio n. 5
0
        private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName, ExtractConfiguration configuration)
        {
            SelectedWeb.EnsureProperty(w => w.Url);
            ProvisioningTemplateCreationInformation creationInformation = null;

            if (configuration != null)
            {
                creationInformation = configuration.ToCreationInformation(SelectedWeb);
            }
            else
            {
                creationInformation = new ProvisioningTemplateCreationInformation(SelectedWeb);
            }

            if (ParameterSpecified(nameof(Handlers)))
            {
                creationInformation.HandlersToProcess = Handlers;
            }
            if (ParameterSpecified(nameof(ExcludeHandlers)))
            {
                foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers)))
                {
                    if (!ExcludeHandlers.Has(handler) && handler != Handlers.All)
                    {
                        Handlers = Handlers | handler;
                    }
                }
                creationInformation.HandlersToProcess = Handlers;
            }

            var extension = "";

            if (packageName != null)
            {
                if (packageName.IndexOf(".", StringComparison.Ordinal) > -1)
                {
                    extension = packageName.Substring(packageName.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
                }
                else
                {
                    packageName += ".pnp";
                    extension    = ".pnp";
                }
            }

            var fileSystemConnector = new FileSystemConnector(path, "");

            if (extension == ".pnp")
            {
                creationInformation.FileConnector = new OpenXMLConnector(packageName, fileSystemConnector);
            }
            else
            {
                creationInformation.FileConnector = fileSystemConnector;
            }
#pragma warning disable 618
            if (ParameterSpecified(nameof(PersistBrandingFiles)))
            {
                creationInformation.PersistBrandingFiles = PersistBrandingFiles;
            }
#pragma warning restore 618
            creationInformation.PersistPublishingFiles       = PersistPublishingFiles;
            creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles;
            if (ParameterSpecified(nameof(IncludeSiteGroups)))
            {
                creationInformation.IncludeSiteGroups = IncludeSiteGroups;
            }
            creationInformation.IncludeTermGroupsSecurity  = IncludeTermGroupsSecurity;
            creationInformation.IncludeSearchConfiguration = IncludeSearchConfiguration;
            if (ParameterSpecified(nameof(IncludeHiddenLists)))
            {
                creationInformation.IncludeHiddenLists = IncludeHiddenLists;
            }
            if (ParameterSpecified(nameof(IncludeAllClientSidePages)))
            {
                creationInformation.IncludeAllClientSidePages = IncludeAllClientSidePages;
            }
            creationInformation.SkipVersionCheck = SkipVersionCheck;
            if (ParameterSpecified(nameof(ContentTypeGroups)) && ContentTypeGroups != null)
            {
                creationInformation.ContentTypeGroupsToInclude = ContentTypeGroups.ToList();
            }
            creationInformation.PersistMultiLanguageResources = PersistMultiLanguageResources;
            if (extension == ".pnp")
            {
                // if file is of pnp format, persist all files
                creationInformation.PersistBrandingFiles          = true;
                creationInformation.PersistPublishingFiles        = true;
                creationInformation.PersistMultiLanguageResources = true;
            }
            if (!string.IsNullOrEmpty(ResourceFilePrefix))
            {
                creationInformation.ResourceFilePrefix = ResourceFilePrefix;
            }
            else
            {
                if (Out != null)
                {
                    FileInfo fileInfo = new FileInfo(Out);
                    var      prefix   = fileInfo.Name;
                    // strip extension, if there is any
                    var indexOfLastDot = prefix.LastIndexOf(".", StringComparison.Ordinal);
                    if (indexOfLastDot > -1)
                    {
                        prefix = prefix.Substring(0, indexOfLastDot);
                    }
                    creationInformation.ResourceFilePrefix = prefix;
                }
            }
            if (ExtensibilityHandlers != null)
            {
                creationInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList();
            }

#pragma warning disable CS0618 // Type or member is obsolete
            if (NoBaseTemplate)
            {
                creationInformation.BaseTemplate = null;
            }
            else
            {
                creationInformation.BaseTemplate = SelectedWeb.GetBaseTemplate();
            }
#pragma warning restore CS0618 // Type or member is obsolete

            creationInformation.ProgressDelegate = (message, step, total) =>
            {
                var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));

                WriteProgress(new ProgressRecord(0, $"Extracting Template from {SelectedWeb.Url}", message)
                {
                    PercentComplete = percentage
                });
                WriteProgress(new ProgressRecord(1, " ", " ")
                {
                    RecordType = ProgressRecordType.Completed
                });
            };
            creationInformation.MessagesDelegate = (message, type) =>
            {
                switch (type)
                {
                case ProvisioningMessageType.Warning:
                {
                    WriteWarning(message);
                    break;
                }

                case ProvisioningMessageType.Progress:
                {
                    var activity = message;
                    if (message.IndexOf("|") > -1)
                    {
                        var messageSplitted = message.Split('|');
                        if (messageSplitted.Length == 4)
                        {
                            var current = double.Parse(messageSplitted[2]);
                            var total   = double.Parse(messageSplitted[3]);
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.Activity          = messageSplitted[0];
                            subProgressRecord.StatusDescription = messageSplitted[1];
                            subProgressRecord.PercentComplete   = Convert.ToInt32((100 / total) * current);
                            WriteProgress(subProgressRecord);
                        }
                        else
                        {
                            subProgressRecord.Activity          = "Processing";
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.StatusDescription = activity;
                            subProgressRecord.PercentComplete   = 0;
                            WriteProgress(subProgressRecord);
                        }
                    }
                    else
                    {
                        subProgressRecord.Activity          = "Processing";
                        subProgressRecord.RecordType        = ProgressRecordType.Processing;
                        subProgressRecord.StatusDescription = activity;
                        subProgressRecord.PercentComplete   = 0;
                        WriteProgress(subProgressRecord);
                    }
                    break;
                }

                case ProvisioningMessageType.Completed:
                {
                    WriteProgress(new ProgressRecord(1, message, " ")
                        {
                            RecordType = ProgressRecordType.Completed
                        });
                    break;
                }
                }
            };

            if (IncludeAllTermGroups)
            {
                creationInformation.IncludeAllTermGroups = true;
            }
            else
            {
                if (IncludeSiteCollectionTermGroup)
                {
                    creationInformation.IncludeSiteCollectionTermGroup = true;
                }
            }

            if (ParameterSpecified(nameof(ExcludeContentTypesFromSyndication)))
            {
                creationInformation.IncludeContentTypesFromSyndication = !ExcludeContentTypesFromSyndication.ToBool();
            }

            if (ListsToExtract != null && ListsToExtract.Count > 0)
            {
                creationInformation.ListsToExtract.AddRange(ListsToExtract);
            }
            ProvisioningTemplate template = null;
            using (var provisioningContext = new PnPProvisioningContext((resource, scope) =>
            {
                // Get Azure AD Token
                if (PnPConnection.CurrentConnection != null)
                {
                    var graphAccessToken = PnPConnection.CurrentConnection.TryGetAccessToken(Enums.TokenAudience.MicrosoftGraph);
                    if (graphAccessToken != null)
                    {
                        // Authenticated using -Graph or using another way to retrieve the accesstoken with Connect-PnPOnline
                        return(Task.FromResult(graphAccessToken));
                    }
                }

                if (PnPConnection.CurrentConnection.PSCredential != null)
                {
                    // Using normal credentials
                    return(Task.FromResult(TokenHandler.AcquireToken(resource, null)));
                }
                else
                {
                    // No token...
                    return(null);
                }
            }))
            {
                template = SelectedWeb.GetProvisioningTemplate(creationInformation);
            }
            // Set metadata for template, if any
            SetTemplateMetadata(template, TemplateDisplayName, TemplateImagePreviewUrl, TemplateProperties);

            if (!OutputInstance)
            {
                var formatter = ProvisioningHelper.GetFormatter(schema);

                if (extension == ".pnp")
                {
                    XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                        creationInformation.FileConnector as OpenXMLConnector);
                    var templateFileName = packageName.Substring(0, packageName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                    provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
                }
                else
                {
                    if (Out != null)
                    {
                        XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(path, "");
                        provider.SaveAs(template, Path.Combine(path, packageName), formatter, TemplateProviderExtensions);
                    }
                    else
                    {
                        var outputStream = formatter.ToFormattedTemplate(template);
                        var reader       = new StreamReader(outputStream);

                        WriteObject(reader.ReadToEnd());
                    }
                }
            }
            else
            {
                WriteObject(template);
            }
        }
        private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName, ExtractConfiguration configuration)
        {
            SelectedWeb.EnsureProperty(w => w.Url);
            ProvisioningTemplateCreationInformation creationInformation = null;

            if (configuration != null)
            {
                creationInformation = configuration.ToCreationInformation(SelectedWeb);
            }
            else
            {
                creationInformation = new ProvisioningTemplateCreationInformation(SelectedWeb);
            }

            if (MyInvocation.BoundParameters.ContainsKey("Handlers"))
            {
                creationInformation.HandlersToProcess = Handlers;
            }
            if (MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers"))
            {
                foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers)))
                {
                    if (!ExcludeHandlers.Has(handler) && handler != Handlers.All)
                    {
                        Handlers = Handlers | handler;
                    }
                }
                creationInformation.HandlersToProcess = Handlers;
            }

            var extension = "";

            if (packageName != null)
            {
                if (packageName.IndexOf(".", StringComparison.Ordinal) > -1)
                {
                    extension = packageName.Substring(packageName.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
                }
                else
                {
                    packageName += ".pnp";
                    extension    = ".pnp";
                }
            }

            var fileSystemConnector = new FileSystemConnector(path, "");

            if (extension == ".pnp")
            {
                creationInformation.FileConnector = new OpenXMLConnector(packageName, fileSystemConnector);
            }
            else
            {
                creationInformation.FileConnector = fileSystemConnector;
            }
#pragma warning disable 618
            if (MyInvocation.BoundParameters.ContainsKey(nameof(PersistBrandingFiles)) || MyInvocation.BoundParameters.ContainsKey(nameof(PersistComposedLookFiles)))
            {
                creationInformation.PersistBrandingFiles = PersistBrandingFiles || PersistComposedLookFiles;
            }
#pragma warning restore 618
            creationInformation.PersistPublishingFiles       = PersistPublishingFiles;
            creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles;
            if (MyInvocation.BoundParameters.ContainsKey(nameof(IncludeSiteGroups)))
            {
                creationInformation.IncludeSiteGroups = IncludeSiteGroups;
            }
            creationInformation.IncludeTermGroupsSecurity  = IncludeTermGroupsSecurity;
            creationInformation.IncludeSearchConfiguration = IncludeSearchConfiguration;
            if (MyInvocation.BoundParameters.ContainsKey(nameof(IncludeHiddenLists)))
            {
                creationInformation.IncludeHiddenLists = IncludeHiddenLists;
            }
#if !SP2013 && !SP2016
            if (MyInvocation.BoundParameters.ContainsKey(nameof(IncludeAllClientSidePages)))
            {
                creationInformation.IncludeAllClientSidePages = IncludeAllClientSidePages;
            }
#endif
            creationInformation.SkipVersionCheck = SkipVersionCheck;
            if (MyInvocation.BoundParameters.ContainsKey(nameof(ContentTypeGroups)) && ContentTypeGroups != null)
            {
                creationInformation.ContentTypeGroupsToInclude = ContentTypeGroups.ToList();
            }
#if !SP2013
            creationInformation.PersistMultiLanguageResources = PersistMultiLanguageResources;
            if (extension == ".pnp")
            {
                // if file is of pnp format, persist all files
                creationInformation.PersistBrandingFiles          = true;
                creationInformation.PersistPublishingFiles        = true;
                creationInformation.PersistMultiLanguageResources = true;
            }
            if (!string.IsNullOrEmpty(ResourceFilePrefix))
            {
                creationInformation.ResourceFilePrefix = ResourceFilePrefix;
            }
            else
            {
                if (Out != null)
                {
                    FileInfo fileInfo = new FileInfo(Out);
                    var      prefix   = fileInfo.Name;
                    // strip extension, if there is any
                    var indexOfLastDot = prefix.LastIndexOf(".", StringComparison.Ordinal);
                    if (indexOfLastDot > -1)
                    {
                        prefix = prefix.Substring(0, indexOfLastDot);
                    }
                    creationInformation.ResourceFilePrefix = prefix;
                }
            }
#endif
            if (ExtensibilityHandlers != null)
            {
                creationInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList();
            }

#pragma warning disable CS0618 // Type or member is obsolete
            if (NoBaseTemplate)
            {
                creationInformation.BaseTemplate = null;
            }
            else
            {
                creationInformation.BaseTemplate = SelectedWeb.GetBaseTemplate();
            }
#pragma warning restore CS0618 // Type or member is obsolete

            creationInformation.ProgressDelegate = (message, step, total) =>
            {
                var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));

                WriteProgress(new ProgressRecord(0, $"Extracting Template from {SelectedWeb.Url}", message)
                {
                    PercentComplete = percentage
                });
            };
            creationInformation.MessagesDelegate = (message, type) =>
            {
                switch (type)
                {
                case ProvisioningMessageType.Warning:
                {
                    WriteWarning(message);
                    break;
                }

                case ProvisioningMessageType.Progress:
                {
                    var activity = message;
                    if (message.IndexOf("|") > -1)
                    {
                        var messageSplitted = message.Split('|');
                        if (messageSplitted.Length == 4)
                        {
                            var current = double.Parse(messageSplitted[2]);
                            var total   = double.Parse(messageSplitted[3]);
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.Activity          = messageSplitted[0];
                            subProgressRecord.StatusDescription = messageSplitted[1];
                            subProgressRecord.PercentComplete   = Convert.ToInt32((100 / total) * current);
                            WriteProgress(subProgressRecord);
                        }
                        else
                        {
                            subProgressRecord.Activity          = "Processing";
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.StatusDescription = activity;
                            subProgressRecord.PercentComplete   = 0;
                            WriteProgress(subProgressRecord);
                        }
                    }
                    else
                    {
                        subProgressRecord.Activity          = "Processing";
                        subProgressRecord.RecordType        = ProgressRecordType.Processing;
                        subProgressRecord.StatusDescription = activity;
                        subProgressRecord.PercentComplete   = 0;
                        WriteProgress(subProgressRecord);
                    }
                    break;
                }

                case ProvisioningMessageType.Completed:
                {
                    WriteProgress(new ProgressRecord(1, message, " ")
                        {
                            RecordType = ProgressRecordType.Completed
                        });
                    break;
                }
                }
            };

            if (IncludeAllTermGroups)
            {
                creationInformation.IncludeAllTermGroups = true;
            }
            else
            {
                if (IncludeSiteCollectionTermGroup)
                {
                    creationInformation.IncludeSiteCollectionTermGroup = true;
                }
            }

            if (MyInvocation.BoundParameters.ContainsKey(nameof(ExcludeContentTypesFromSyndication)))
            {
                creationInformation.IncludeContentTypesFromSyndication = !ExcludeContentTypesFromSyndication.ToBool();
            }

            if (ListsToExtract != null && ListsToExtract.Count > 0)
            {
                creationInformation.ListsToExtract.AddRange(ListsToExtract);
            }

            var template = SelectedWeb.GetProvisioningTemplate(creationInformation);

            // Set metadata for template, if any
            SetTemplateMetadata(template, TemplateDisplayName, TemplateImagePreviewUrl, TemplateProperties);

            if (!OutputInstance)
            {
                ITemplateFormatter formatter = null;
                switch (schema)
                {
                case XMLPnPSchemaVersion.LATEST:
                {
                    formatter = XMLPnPSchemaFormatter.LatestFormatter;
                    break;
                }

                case XMLPnPSchemaVersion.V201503:
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_03);
#pragma warning restore CS0618 // Type or member is obsolete
                    break;
                }

                case XMLPnPSchemaVersion.V201505:
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_05);
#pragma warning restore CS0618 // Type or member is obsolete
                    break;
                }

                case XMLPnPSchemaVersion.V201508:
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_08);
#pragma warning restore CS0618 // Type or member is obsolete
                    break;
                }

                case XMLPnPSchemaVersion.V201512:
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_12);
#pragma warning restore CS0618 // Type or member is obsolete
                    break;
                }

                case XMLPnPSchemaVersion.V201605:
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2016_05);
#pragma warning restore CS0618 // Type or member is obsolete
                    break;
                }

                case XMLPnPSchemaVersion.V201705:
                {
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2017_05);
                    break;
                }

                case XMLPnPSchemaVersion.V201801:
                {
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2018_01);
                    break;
                }

                case XMLPnPSchemaVersion.V201805:
                {
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2018_05);
                    break;
                }

                case XMLPnPSchemaVersion.V201807:
                {
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2018_07);
                    break;
                }

                case XMLPnPSchemaVersion.V201903:
                {
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2019_03);
                    break;
                }

                case XMLPnPSchemaVersion.V201909:
                {
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2019_09);
                    break;
                }
                }

                if (extension == ".pnp")
                {
                    IsolatedStorage.InitializeIsolatedStorage();

                    XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                        creationInformation.FileConnector as OpenXMLConnector);
                    var templateFileName = packageName.Substring(0, packageName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                    provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
                }
                else
                {
                    if (Out != null)
                    {
                        XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(path, "");
                        provider.SaveAs(template, Path.Combine(path, packageName), formatter, TemplateProviderExtensions);
                    }
                    else
                    {
                        var outputStream = formatter.ToFormattedTemplate(template);
                        var reader       = new StreamReader(outputStream);

                        WriteObject(reader.ReadToEnd());
                    }
                }
            }
            else
            {
                WriteObject(template);
            }
        }