protected override void ProcessRecord()
        {
            // Determine the output file name and path
            string outFileName = Path.GetFileName(Out);

            if (!Path.IsPathRooted(Out))
            {
                Out = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Out);
            }

            bool proceed = false;

            if (System.IO.File.Exists(Out))
            {
                if (Force || ShouldContinue(string.Format(Properties.Resources.File0ExistsOverwrite, Out),
                                            Properties.Resources.Confirm))
                {
                    proceed = true;
                }
            }
            else
            {
                proceed = true;
            }

            string outPath = new FileInfo(Out).DirectoryName;

            // Determine if it is an .XML or a .PNP file
            var extension = "";

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

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

            ITemplateFormatter formatter = XMLPnPSchemaFormatter.LatestFormatter;

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                    Out, fileSystemConnector);
                var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(InputInstance, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(outPath, "");
                provider.SaveAs(InputInstance, Out, formatter, TemplateProviderExtensions);
            }
        }
        protected override void ProcessRecord()
        {
            if (!System.IO.Path.IsPathRooted(Path))
            {
                Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
            }
            // Load the template
            var template = LoadProvisioningTemplate
                           .LoadProvisioningTemplateFromFile(Path,
                                                             TemplateProviderExtensions);

            if (template == null)
            {
                throw new ApplicationException("Invalid template file!");
            }

            // Load the file and add it to the .PNP file
            using (var fs = new FileStream(Source, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                Folder = Folder.Replace("\\", "/");

                var fileName  = Source.IndexOf("\\") > 0 ? Source.Substring(Source.LastIndexOf("\\") + 1) : Source;
                var container = !string.IsNullOrEmpty(Container) ? Container : string.Empty;
                var source    = !string.IsNullOrEmpty(container) ? (container + "/" + fileName) : fileName;

                template.Connector.SaveFileStream(fileName, container, fs);

                if (template.Connector is ICommitableFileConnector)
                {
                    ((ICommitableFileConnector)template.Connector).Commit();
                }

                template.Files.Add(new OfficeDevPnP.Core.Framework.Provisioning.Model.File
                {
                    Src       = source,
                    Folder    = Folder,
                    Overwrite = true,
                });

                // Determine the output file name and path
                var outFileName = System.IO.Path.GetFileName(Path);
                var outPath     = new FileInfo(Path).DirectoryName;

                var fileSystemConnector = new FileSystemConnector(outPath, "");
                var formatter           = XMLPnPSchemaFormatter.LatestFormatter;
                var extension           = new FileInfo(Path).Extension.ToLowerInvariant();
                if (extension == ".pnp")
                {
                    XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(outPath, fileSystemConnector));
                    var templateFileName         = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                    provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
                }
                else
                {
                    XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(Path, "");
                    provider.SaveAs(template, Path, formatter, TemplateProviderExtensions);
                }
            }
        }
Exemplo n.º 3
0
        private void btnSaveTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                var template = (ProvisioningTemplate)pgTemplate.SelectedObject;
                if (template != null)
                {
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        var fileFullPath    = saveFileDialog1.FileName;
                        var fileInfo        = new System.IO.FileInfo(fileFullPath);
                        var pnpTemplatePath = fileInfo.DirectoryName;

                        var pnpFileName = fileInfo.Name;
                        if (pnpFileName.EndsWith(".pnp", StringComparison.InvariantCultureIgnoreCase))
                        {
                            pnpFileName = pnpFileName.Substring(0, pnpFileName.Length - 4);
                        }
                        var web  = Context.Web;
                        var ptci = new ProvisioningTemplateCreationInformation(web);
                        var fileSystemConnector = new FileSystemConnector(pnpTemplatePath, "");
                        ptci.FileConnector = new OpenXMLConnector($"{pnpFileName}.pnp", fileSystemConnector);
                        XMLTemplateProvider provider =
                            new XMLOpenXMLTemplateProvider((OpenXMLConnector)ptci.FileConnector);
                        provider.SaveAs(template, $"{pnpFileName}.xml");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 4
0
        protected override void ProcessRecord()
        {
            if (String.IsNullOrEmpty(Source))
            {
                throw new ArgumentNullException("Source");
            }

            if (String.IsNullOrEmpty(Folder))
            {
                throw new ArgumentNullException("Folder");
            }

            // Load the template
            ProvisioningTemplate template = LoadProvisioningTemplate
                                            .LoadProvisioningTemplateFromFile(Path,
                                                                              SessionState.Path.CurrentFileSystemLocation.Path,
                                                                              TemplateProviderExtensions);

            if (template == null)
            {
                throw new ApplicationException("Invalid template file!");
            }

            // Load the file and add it to the .PNP file
            using (FileStream fs = new FileStream(Source, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                Folder = Folder.Replace("\\", "/");

                String fileName  = Source.IndexOf("\\") > 0 ? Source.Substring(Source.LastIndexOf("\\") + 1) : Source;
                String container = !String.IsNullOrEmpty(Container) ? Container : String.Empty;
                String source    = !String.IsNullOrEmpty(container) ? (container + "/" + fileName) : fileName;

                template.Connector.SaveFileStream(fileName, container, fs);

                if (template.Connector is ICommitableFileConnector)
                {
                    ((ICommitableFileConnector)template.Connector).Commit();
                }

                template.Files.Add(new OfficeDevPnP.Core.Framework.Provisioning.Model.File {
                    Src       = source,
                    Folder    = Folder,
                    Overwrite = true,
                });

                // Determine the output file name and path
                string outFileName = System.IO.Path.GetFileName(Path);
                string outPath     = new System.IO.FileInfo(Path).DirectoryName;

                // Save the template back to the storage
                var fileSystemConnector      = new FileSystemConnector(outPath, "");
                ITemplateFormatter formatter = XMLPnPSchemaFormatter.LatestFormatter;

                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                    Path, fileSystemConnector);
                var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
            }
        }
Exemplo n.º 5
0
        protected override void ProcessRecord()
        {
            if (!System.IO.Path.IsPathRooted(Path))
            {
                Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
            }
            // Load the template
            ProvisioningTemplate template = ReadProvisioningTemplate
                                            .LoadProvisioningTemplateFromFile(Path,
                                                                              TemplateProviderExtensions, (e) =>
            {
                WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null));
            });

            if (template == null)
            {
                throw new ApplicationException("Invalid template file!");
            }

            var fileToRemove = template.Files.FirstOrDefault(f => f.Src == FilePath);

            if (fileToRemove != null)
            {
                template.Files.Remove(fileToRemove);
                template.Connector.DeleteFile(FilePath);

                if (template.Connector is ICommitableFileConnector)
                {
                    ((ICommitableFileConnector)template.Connector).Commit();
                }

                // Determine the output file name and path
                var outFileName = System.IO.Path.GetFileName(Path);
                var outPath     = new FileInfo(Path).DirectoryName;

                var fileSystemConnector = new FileSystemConnector(outPath, "");
                var formatter           = XMLPnPSchemaFormatter.LatestFormatter;
                var extension           = new FileInfo(Path).Extension.ToLowerInvariant();
                if (extension == ".pnp")
                {
                    XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(outPath, fileSystemConnector));
                    var templateFileName         = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                    provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
                }
                else
                {
                    XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(Path, "");
                    provider.SaveAs(template, Path, formatter, TemplateProviderExtensions);
                }
            }
        }
Exemplo n.º 6
0
        private void AddFileToTemplate(ProvisioningTemplate template, Stream fs, string folder, string fileName, string container)
        {
            var source = !string.IsNullOrEmpty(container) ? (container + "/" + fileName) : fileName;

            template.Connector.SaveFileStream(fileName, container, fs);

            if (template.Connector is ICommitableFileConnector connector)
            {
                connector.Commit();
            }

            var existing = template.Files.FirstOrDefault(f =>
                                                         f.Src == $"{container}/{fileName}" &&
                                                         f.Folder == folder);

            if (existing != null)
            {
                template.Files.Remove(existing);
            }

            var newFile = new PnP.Framework.Provisioning.Model.File
            {
                Src       = source,
                Folder    = folder,
                Level     = FileLevel,
                Overwrite = FileOverwrite,
            };

            template.Files.Add(newFile);

            // Determine the output file name and path
            var outFileName = System.IO.Path.GetFileName(Path);
            var outPath     = new FileInfo(Path).DirectoryName;

            var fileSystemConnector = new FileSystemConnector(outPath, "");
            var formatter           = XMLPnPSchemaFormatter.LatestFormatter;
            var extension           = new FileInfo(Path).Extension.ToLowerInvariant();

            if (extension == ".pnp")
            {
                var provider         = new XMLOpenXMLTemplateProvider(template.Connector as OpenXMLConnector);
                var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(Path, "");
                provider.SaveAs(template, Path, formatter, TemplateProviderExtensions);
            }
        }
Exemplo n.º 7
0
        protected override void ProcessRecord()
        {
            if (String.IsNullOrEmpty(FilePath))
            {
                throw new ArgumentNullException("FilePath");
            }

            // Load the template
            ProvisioningTemplate template = LoadProvisioningTemplate
                                            .LoadProvisioningTemplateFromFile(Path,
                                                                              SessionState.Path.CurrentFileSystemLocation.Path,
                                                                              TemplateProviderExtensions);

            if (template == null)
            {
                throw new ApplicationException("Invalid template file!");
            }

            var fileToRemove = template.Files.FirstOrDefault(f => f.Src == FilePath);

            if (fileToRemove != null)
            {
                template.Files.Remove(fileToRemove);
                template.Connector.DeleteFile(FilePath);

                if (template.Connector is ICommitableFileConnector)
                {
                    ((ICommitableFileConnector)template.Connector).Commit();
                }

                // Determine the output file name and path
                string outFileName = System.IO.Path.GetFileName(Path);
                string outPath     = new System.IO.FileInfo(Path).DirectoryName;

                // Save the template back to the storage
                var fileSystemConnector      = new FileSystemConnector(outPath, "");
                ITemplateFormatter formatter = XMLPnPSchemaFormatter.LatestFormatter;

                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                    Path, fileSystemConnector);
                var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
            }
        }
Exemplo n.º 8
0
        protected override void ProcessRecord()
        {
            // Determine the output file name and path
            string outFileName = System.IO.Path.GetFileName(Out);
            string outPath     = new System.IO.FileInfo(Out).DirectoryName;

            // Determine if it is an .XML or a .PNP file
            var extension = "";

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

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

            ITemplateFormatter formatter = XMLPnPSchemaFormatter.LatestFormatter;

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                    Out, fileSystemConnector);
                var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(InputInstance, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(outPath, "");
                provider.SaveAs(InputInstance, Out, formatter, TemplateProviderExtensions);
            }
        }
        private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName)
        {
            SelectedWeb.EnsureProperty(w => w.Url);

            var creationInformation = new ProvisioningTemplateCreationInformation(SelectedWeb);

            creationInformation.HandlersToProcess = Handlers.Lists;

            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;
            }

            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 (List != null && List.Count > 0)
            {
                creationInformation.ListsToExtract.AddRange(List);
            }

            var template = SelectedWeb.GetProvisioningTemplate(creationInformation);



            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, null);
                }
                else
                {
                    if (Out != null)
                    {
                        XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(path, "");
                        provider.SaveAs(template, Path.Combine(path, packageName), formatter, null);
                    }
                    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)
        {
            SelectedWeb.EnsureProperty(w => w.Url);

            var 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
            creationInformation.PersistBrandingFiles = PersistBrandingFiles || PersistComposedLookFiles;
#pragma warning restore 618
            creationInformation.PersistPublishingFiles       = PersistPublishingFiles;
            creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles;
            creationInformation.IncludeSiteGroups            = IncludeSiteGroups;
            creationInformation.IncludeTermGroupsSecurity    = IncludeTermGroupsSecurity;
            creationInformation.IncludeSearchConfiguration   = IncludeSearchConfiguration;
            creationInformation.SkipVersionCheck             = SkipVersionCheck;
            if (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.Substring(0, fileInfo.Name.LastIndexOf(".", StringComparison.Ordinal));
                    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;
                }
            }

            creationInformation.IncludeContentTypesFromSyndication = !ExcludeContentTypesFromSyndication.ToBool();

            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:
                {
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_12);
                    break;
                }

                case XMLPnPSchemaVersion.V201605:
                {
                    formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2016_05);
                    break;
                }

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

                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);
            }
        }
Exemplo n.º 11
0
        private void SaveProvisioningTemplateInternal(ClientContext context, GetProvisioningTemplateJob job, Boolean globalRepository = true)
        {
            // Fix the job filename if it is missing the .pnp extension
            if (!job.FileName.ToLower().EndsWith(".pnp"))
            {
                job.FileName += ".pnp";
            }

            // Get the Access Token from the current context
            //var accessToken = "Bearer " + context.GetAccessToken();
            var accessToken = context.GetAccessToken();

            Console.WriteLine("Bearer " + accessToken);

            // Get a reference to the target web site
            Web web = context.Web;

            context.Load(web, w => w.Url, w => w.ServerRelativeUrl);
            context.ExecuteQueryRetry();

            // Prepare the support variables
            ClientContext repositoryContext = null;
            Web           repositoryWeb     = null;

            // Define whether we need to use the global infrastructural repository or the local one
            if (globalRepository)
            {
                // Get a reference to the global repository web site and context
                repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(
                    PnPPartnerPackSettings.InfrastructureSiteUrl);
            }
            else
            {
                // Get a reference to the local repository web site and context
                repositoryContext = web.Context.GetSiteCollectionContext();
            }

            using (repositoryContext)
            {
                repositoryWeb = repositoryContext.Site.RootWeb;
                repositoryContext.Load(repositoryWeb, w => w.Url);
                repositoryContext.ExecuteQueryRetry();

                // Configure the XML SharePoint provider for the Infrastructural Site Collection
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(job.FileName,
                                                                              new SharePointConnector(repositoryContext, repositoryWeb.Url,
                                                                                                      PnPPartnerPackConstants.PnPProvisioningTemplates));

                ProvisioningTemplateCreationInformation ptci =
                    new ProvisioningTemplateCreationInformation(web);
                ptci.FileConnector                  = provider.Connector;
                ptci.IncludeAllTermGroups           = job.IncludeAllTermGroups;
                ptci.IncludeSearchConfiguration     = job.IncludeSearchConfiguration;
                ptci.IncludeSiteCollectionTermGroup = job.IncludeSiteCollectionTermGroup;
                ptci.IncludeSiteGroups              = job.IncludeSiteGroups;
                ptci.PersistBrandingFiles           = job.PersistComposedLookFiles;

                // We do intentionally remove taxonomies and search, which are not supported
                // in the AppOnly Authorization model
                // For further details, see the PnP Partner Pack documentation
                ptci.HandlersToProcess ^= Handlers.TermGroups;
                ptci.HandlersToProcess ^= Handlers.SearchSettings;

                // Extract the current template
                ProvisioningTemplate templateToSave = web.GetProvisioningTemplate(ptci);

                templateToSave.Description = job.Description;
                templateToSave.DisplayName = job.Title;

                if (job.PersistComposedLookFiles)
                {
                    // Create Theme Entity object
                    ThemeEntity themeEntity = web.GetCurrentComposedLook();

                    foreach (var p in themeEntity.GetType().GetProperties().Where(p => p.GetGetMethod().GetParameters().Count() == 0))
                    {
                        string propName  = p.Name;
                        string propValue = Convert.ToString(p.GetValue(themeEntity, null));

                        if (propName == "Theme")
                        {
                            propName = "ColorFile";
                        }
                        else if (propName == "Font")
                        {
                            propName = "FontFile";
                        }
                        else if (propName == "BackgroundImage")
                        {
                            propValue = "PlaceHolderValue";
                        }
                        else if (propName == "Name" && String.IsNullOrEmpty(propValue))
                        {
                            propValue = "CustomTheme";
                        }

                        string fileName    = propValue.Substring(propValue.LastIndexOf("/") + 1);
                        string relativeURL = propValue.Substring(0, propValue.LastIndexOf("/") + 1);

                        // Update template Files
                        if (propName != "Name" && propName != "IsCustomComposedLook" && !String.IsNullOrEmpty(propValue))
                        {
                            var property = templateToSave.ComposedLook.GetType().GetProperty(propName);

                            try
                            {
                                string folderPath = "";
                                Stream fileStream = null;

                                if (propName == "BackgroundImage")
                                {
                                    if (job.templateBackgroundImgFile != null)
                                    {
                                        folderPath = "{site}/SiteAssets";
                                        fileName   = job.FileName.ToLower().Replace(".pnp", ".png");
                                        fileStream = job.templateBackgroundImgFile.ToStream();
                                        Console.WriteLine("fileName: " + fileName);
                                        Console.WriteLine("fileStream: " + fileStream);
                                        templateToSave.ComposedLook.BackgroundFile = String.Format("{{sitecollection}}/SiteAssets/{0}", fileName);
                                    }
                                }
                                else if (propName.Contains("MasterPage"))
                                {
                                    folderPath = "{masterpagecatalog}";
                                    var strUrl = String.Format("{0}/_api/web/getfilebyserverrelativeurl('{1}{2}')/$value", web.Url, web.ServerRelativeUrl, propValue);
                                    fileStream = HttpHelper.MakeGetRequestForStream(strUrl, "application/octet-stream", accessToken);
                                    property.SetValue(templateToSave.ComposedLook, String.Format("{{masterpagecatalog}}/{0}", fileName), new object[] { });
                                }
                                else
                                {
                                    folderPath = "{themecatalog}/15";
                                    var strUrl = String.Format("{0}/_api/web/getfilebyserverrelativeurl('{1}{2}')/$value", web.Url, web.ServerRelativeUrl, propValue);
                                    fileStream = HttpHelper.MakeGetRequestForStream(strUrl, "application/octet-stream", accessToken);
                                    property.SetValue(templateToSave.ComposedLook, String.Format("{{themecatalog}}/15/{0}", fileName), new object[] { });
                                }

                                Console.WriteLine("Saving files: {0}, {1}", fileName, fileStream);
                                provider.Connector.SaveFileStream(fileName, fileStream);

                                Console.WriteLine("File Paths: {0}, {1}", fileName, folderPath);
                                templateToSave.Files.Add(new OfficeDevPnP.Core.Framework.Provisioning.Model.File
                                {
                                    Src       = fileName,
                                    Folder    = folderPath,
                                    Overwrite = true,
                                });

                                Console.WriteLine("Files saved: {0}, {1}", fileName, folderPath);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }
                        else if (propName == "Name")
                        {
                            var property = templateToSave.ComposedLook.GetType().GetProperty(propName);

                            property.SetValue(templateToSave.ComposedLook, fileName, new object[] { });
                        }
                    }

                    if (job.templateAltCSSFile != null)
                    {
                        //TODO: Add handling for native Alternate CSS
                        //web.AlternateCssUrl;
                        string folderPath = "{site}/SiteAssets";
                        string fileName   = job.FileName.ToLower().Replace(".pnp", ".css");
                        Stream fileStream = job.templateAltCSSFile.ToStream();

                        provider.Connector.SaveFileStream(fileName, fileStream);

                        templateToSave.WebSettings = new WebSettings
                        {
                            AlternateCSS = String.Format("{{sitecollection}}/SiteAssets/{0}", fileName),
                        };

                        Console.WriteLine("File Paths: {0}, {1}", fileName, folderPath);
                        templateToSave.Files.Add(new OfficeDevPnP.Core.Framework.Provisioning.Model.File
                        {
                            Src       = fileName,
                            Folder    = folderPath,
                            Overwrite = true,
                        });
                    }
                }

                // Save template image preview in folder
                Microsoft.SharePoint.Client.Folder templatesFolder = repositoryWeb.GetFolderByServerRelativeUrl(PnPPartnerPackConstants.PnPProvisioningTemplates);
                repositoryContext.Load(templatesFolder, f => f.ServerRelativeUrl, f => f.Name);
                repositoryContext.ExecuteQueryRetry();

                // If there is a preview image
                if (job.TemplateImageFile != null)
                {
                    // Determine the preview image file name
                    String previewImageFileName = job.FileName.ToLower().Replace(".pnp", "_preview.png");

                    // Save the preview image inside the Open XML package
                    provider.Connector.SaveFileStream(previewImageFileName, job.TemplateImageFile.ToStream());

                    // And store URL in the XML file
                    templateToSave.ImagePreviewUrl = String.Format("{0}{1}/{2}/{3}/{4}",
                                                                   repositoryWeb.Url.ToLower().StartsWith("https") ? "pnps" : "pnp",
                                                                   repositoryWeb.Url.Substring(repositoryWeb.Url.IndexOf("://")),
                                                                   templatesFolder.Name, job.FileName, previewImageFileName);
                }

                // And save it on the file system
                provider.SaveAs(templateToSave, job.FileName.ToLower().Replace(".pnp", ".xml"));

                Microsoft.SharePoint.Client.File templateFile = templatesFolder.GetFile(job.FileName);
                ListItem item = templateFile.ListItemAllFields;

                item[PnPPartnerPackConstants.ContentTypeIdField]               = PnPPartnerPackConstants.PnPProvisioningTemplateContentTypeId;
                item[PnPPartnerPackConstants.TitleField]                       = job.Title;
                item[PnPPartnerPackConstants.PnPProvisioningTemplateScope]     = job.Scope.ToString();
                item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl] = job.SourceSiteUrl;

                item.Update();

                repositoryContext.ExecuteQueryRetry();
            }
        }
        protected override void ProcessRecord()
        {
            if (MyInvocation.InvocationName.ToLower() == "save-pnpprovisioninghierarchy")
            {
                WriteWarning("Save-PnPProvisioningHierarchy has been deprecated. Use Save-PnPTenantTemplate instead.");
            }
            // Determine the output file name and path
            string outFileName = Path.GetFileName(Out);

            if (!Path.IsPathRooted(Out))
            {
                Out = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Out);
            }

            bool proceed = false;

            if (System.IO.File.Exists(Out))
            {
                if (Force || ShouldContinue(string.Format(Properties.Resources.File0ExistsOverwrite, Out),
                                            Properties.Resources.Confirm))
                {
                    System.IO.File.Delete(Out);
                    proceed = true;
                }
            }
            else
            {
                proceed = true;
            }

            string outPath = new FileInfo(Out).DirectoryName;

            // Determine if it is an .XML or a .PNP file
            var extension = "";

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

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

            ITemplateFormatter formatter = XMLPnPSchemaFormatter.LatestFormatter;

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

                var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                    Out, fileSystemConnector, templateFileName: templateFileName);
                WriteObject("Processing template");
                provider.SaveAs(Template, templateFileName);
                ProcessFiles(Out, fileSystemConnector, provider.Connector);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(outPath, "");
                provider.SaveAs(Template, Out);
            }
        }
Exemplo n.º 13
0
        private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName)
        {
            SelectedWeb.EnsureProperty(w => w.Url);

            var creationInformation = new ProvisioningTemplateCreationInformation(SelectedWeb);

            creationInformation.HandlersToProcess = Handlers.Lists;

            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;
            }

            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 (List != null && List.Count > 0)
            {
                creationInformation.ListsToExtract.AddRange(List);
            }

            var template = SelectedWeb.GetProvisioningTemplate(creationInformation);



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

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

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

                        WriteObject(reader.ReadToEnd());
                    }
                }
            }
            else
            {
                WriteObject(template);
            }
        }
Exemplo n.º 14
0
        protected override void ProcessRecord()
        {
            var templateObject = Template.GetTemplate(SessionState.Path.CurrentFileSystemLocation.Path, (e) =>
            {
                WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null));
            });

            // Determine the output file name and path
            string outFileName = Path.GetFileName(Out);

            if (!Path.IsPathRooted(Out))
            {
                Out = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Out);
            }

            bool proceed = false;

            if (System.IO.File.Exists(Out))
            {
                if (Force || ShouldContinue(string.Format(Properties.Resources.File0ExistsOverwrite, Out),
                                            Properties.Resources.Confirm))
                {
                    System.IO.File.Delete(Out);
                    proceed = true;
                }
            }
            else
            {
                proceed = true;
            }

            string outPath = new FileInfo(Out).DirectoryName;

            // Determine if it is an .XML or a .PNP file
            var extension = "";

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

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

            var formatter = ProvisioningHelper.GetFormatter(Schema);

            if (extension == ".pnp")
            {
                var templateFileName         = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                    Out, fileSystemConnector, templateFileName: templateFileName);
                WriteObject("Processing template");
                provider.SaveAs(templateObject, templateFileName, formatter);
                ProcessFiles(templateObject, Out, fileSystemConnector, provider.Connector, (message) =>
                {
                    WriteObject(message);
                });
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(outPath, "");
                provider.SaveAs(templateObject, Out, formatter);
            }
        }
Exemplo n.º 15
0
        private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName)
        {
            SelectedWeb.EnsureProperty(w => w.Url);

            var creationInformation = new ProvisioningTemplateCreationInformation(SelectedWeb);

            if (this.MyInvocation.BoundParameters.ContainsKey("Handlers"))
            {
                creationInformation.HandlersToProcess = Handlers;
            }
            if (this.MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers"))
            {
                foreach (var handler in (OfficeDevPnP.Core.Framework.Provisioning.Model.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(".") > -1)
                {
                    extension = packageName.Substring(packageName.LastIndexOf(".")).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
            creationInformation.PersistBrandingFiles = PersistBrandingFiles || PersistComposedLookFiles;
#pragma warning restore 618
            creationInformation.PersistPublishingFiles       = PersistPublishingFiles;
            creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles;
            creationInformation.IncludeSiteGroups            = IncludeSiteGroups;
            creationInformation.IncludeTermGroupsSecurity    = IncludeTermGroupsSecurity;
#if !SP2013
            creationInformation.PersistMultiLanguageResources = PersistMultiLanguageResources;
            if (!string.IsNullOrEmpty(ResourceFilePrefix))
            {
                creationInformation.ResourceFilePrefix = ResourceFilePrefix;
            }
            else
            {
                if (Out != null)
                {
                    FileInfo fileInfo = new FileInfo(Out);
                    var      prefix   = fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf("."));
                    creationInformation.ResourceFilePrefix = prefix;
                }
            }
#endif
            if (ExtensibilityHandlers != null)
            {
                creationInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList <ExtensibilityHandler>();
            }

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

            creationInformation.ProgressDelegate = (message, step, total) =>
            {
                WriteProgress(new ProgressRecord(0, string.Format("Extracting Template from {0}", SelectedWeb.Url), message)
                {
                    PercentComplete = (100 / total) * step
                });
            };
            creationInformation.MessagesDelegate = (message, type) =>
            {
                if (type == ProvisioningMessageType.Warning)
                {
                    WriteWarning(message);
                }
            };

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

            var template = SelectedWeb.GetProvisioningTemplate(creationInformation);

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

            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:
            {
                formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_08);
                break;
            }

            case XMLPnPSchemaVersion.V201512:
            {
                formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_12);
                break;
            }
            }

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(

                    creationInformation.FileConnector as OpenXMLConnector);
                var templateFileName = packageName.Substring(0, packageName.LastIndexOf(".")) + ".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);
                    StreamReader reader        = new StreamReader(_outputStream);

                    WriteObject(reader.ReadToEnd());
                }
            }
        }
Exemplo n.º 16
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);
            }
        }
Exemplo n.º 17
0
        protected override void ProcessRecord()
        {
            if (MyInvocation.InvocationName.ToLower() == "save-pnpprovisioninghierarchy")
            {
                WriteWarning("Save-PnPProvisioningHierarchy has been deprecated. Use Save-PnPTenantTemplate instead.");
            }
            // Determine the output file name and path
            string outFileName = Path.GetFileName(Out);

            if (!Path.IsPathRooted(Out))
            {
                Out = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Out);
            }

            bool proceed = false;

            if (System.IO.File.Exists(Out))
            {
                if (Force || ShouldContinue(string.Format(Properties.Resources.File0ExistsOverwrite, Out),
                                            Properties.Resources.Confirm))
                {
                    System.IO.File.Delete(Out);
                    proceed = true;
                }
            }
            else
            {
                proceed = true;
            }

            string outPath = new FileInfo(Out).DirectoryName;

            // Determine if it is an .XML or a .PNP file
            var extension = "";

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

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

            ITemplateFormatter formatter = XMLPnPSchemaFormatter.LatestFormatter;

            if (extension == ".pnp")
            {
                var useNewEvidence = false;
                try
                {
                    var usfdAttempt1 = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForDomain(); // this will fail when the current AppDomain Evidence is instantiated via COM or in PowerShell
                }
                catch (Exception e)
                {
                    useNewEvidence = true;
                }

                if (useNewEvidence)
                {
                    var replacementEvidence = new System.Security.Policy.Evidence();
                    replacementEvidence.AddHostEvidence(new System.Security.Policy.Zone(System.Security.SecurityZone.MyComputer));

                    var currentAppDomain      = System.Threading.Thread.GetDomain();
                    var securityIdentityField = currentAppDomain.GetType().GetField("_SecurityIdentity", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                    securityIdentityField.SetValue(currentAppDomain, replacementEvidence);
                }

                var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                    Out, fileSystemConnector, templateFileName: templateFileName);
                WriteObject("Processing template");
                provider.SaveAs(Template, templateFileName);
                ProcessFiles(Out, fileSystemConnector, provider.Connector);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(outPath, "");
                provider.SaveAs(Template, Out);
            }
        }
Exemplo n.º 18
0
        public static ProvisioningTemplate PrepareBrandingTemplate(ClientContext repositoryContext, BrandingSettings brandingSettings)
        {
            var repositoryWeb = repositoryContext.Site.RootWeb;

            repositoryContext.Load(repositoryWeb, w => w.Url);
            repositoryContext.ExecuteQueryRetry();

            var refererUri   = new Uri(repositoryWeb.Url);
            var refererValue = $"{refererUri.Scheme}://{refererUri.Host}/";

            var templateId = Guid.NewGuid();

            // Prepare an OpenXML provider
            XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider($"{templateId}.pnp",
                                                                          new SharePointConnector(repositoryContext, repositoryWeb.Url,
                                                                                                  PnPPartnerPackConstants.PnPProvisioningTemplates));

            // Prepare the branding provisioning template
            var template = new ProvisioningTemplate()
            {
                Id          = $"Branding-{Guid.NewGuid()}",
                DisplayName = "Branding Template",
            };

            template.WebSettings = new WebSettings
            {
                AlternateCSS = brandingSettings.CSSOverrideUrl,
                SiteLogo     = brandingSettings.LogoImageUrl,
            };

            template.ComposedLook = new ComposedLook()
            {
                Name = "SharePointBranding",
            };

            if (!String.IsNullOrEmpty(brandingSettings.BackgroundImageUrl))
            {
                var backgroundImageFileName   = brandingSettings.BackgroundImageUrl.Substring(brandingSettings.BackgroundImageUrl.LastIndexOf("/") + 1);
                var backgroundImageFileStream = HttpHelper.MakeGetRequestForStream(brandingSettings.BackgroundImageUrl, "application/octet-stream", referer: refererValue);
                template.ComposedLook.BackgroundFile = String.Format("{{sitecollection}}/SiteAssets/{0}", backgroundImageFileName);
                provider.Connector.SaveFileStream(backgroundImageFileName, backgroundImageFileStream);

                template.Files.Add(new Core.Framework.Provisioning.Model.File
                {
                    Src       = backgroundImageFileName,
                    Folder    = "SiteAssets",
                    Overwrite = true,
                });
            }
            else
            {
                template.ComposedLook.BackgroundFile = String.Empty;
            }

            if (!String.IsNullOrEmpty(brandingSettings.FontFileUrl))
            {
                var fontFileName   = brandingSettings.FontFileUrl.Substring(brandingSettings.FontFileUrl.LastIndexOf("/") + 1);
                var fontFileStream = HttpHelper.MakeGetRequestForStream(brandingSettings.FontFileUrl, "application/octet-stream", referer: refererValue);
                template.ComposedLook.FontFile = String.Format("{{themecatalog}}/15/{0}", fontFileName);
                provider.Connector.SaveFileStream(fontFileName, fontFileStream);

                template.Files.Add(new Core.Framework.Provisioning.Model.File
                {
                    Src       = fontFileName,
                    Folder    = "{themecatalog}/15",
                    Overwrite = true,
                });
            }
            else
            {
                template.ComposedLook.FontFile = String.Empty;
            }

            if (!String.IsNullOrEmpty(brandingSettings.ColorFileUrl))
            {
                var colorFileName   = brandingSettings.ColorFileUrl.Substring(brandingSettings.ColorFileUrl.LastIndexOf("/") + 1);
                var colorFileStream = HttpHelper.MakeGetRequestForStream(brandingSettings.ColorFileUrl, "application/octet-stream", referer: refererValue);
                template.ComposedLook.ColorFile = String.Format("{{themecatalog}}/15/{0}", colorFileName);
                provider.Connector.SaveFileStream(colorFileName, colorFileStream);

                template.Files.Add(new Core.Framework.Provisioning.Model.File
                {
                    Src       = colorFileName,
                    Folder    = "{themecatalog}/15",
                    Overwrite = true,
                });
            }
            else
            {
                template.ComposedLook.ColorFile = String.Empty;
            }

            // Save the template, ready to be applied
            provider.SaveAs(template, $"{templateId}.xml");

            // Re-open the template provider just saved
            provider = new XMLOpenXMLTemplateProvider($"{templateId}.pnp",
                                                      new SharePointConnector(repositoryContext, repositoryWeb.Url,
                                                                              PnPPartnerPackConstants.PnPProvisioningTemplates));

            // Set the connector of the template, in order to being able to retrieve support files
            template.Connector = provider.Connector;

            return(template);
        }
Exemplo n.º 19
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);
            }
        }
        private void SaveProvisioningTemplateInternal(ClientContext context, GetProvisioningTemplateJob job, Boolean globalRepository = true)
        {
            // Fix the job filename if it is missing the .pnp extension
            if (!job.FileName.ToLower().EndsWith(".pnp"))
            {
                job.FileName += ".pnp";
            }

            // Get a reference to the target web site
            Web web = context.Web;

            context.Load(web, w => w.Url);
            context.ExecuteQueryRetry();

            // Prepare the support variables
            ClientContext repositoryContext = null;
            Web           repositoryWeb     = null;

            // Define whether we need to use the global infrastructural repository or the local one
            if (globalRepository)
            {
                // Get a reference to the global repository web site and context
                repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(
                    PnPPartnerPackSettings.InfrastructureSiteUrl);
            }
            else
            {
                // Get a reference to the local repository web site and context
                repositoryContext = web.Context.GetSiteCollectionContext();
            }

            using (repositoryContext)
            {
                repositoryWeb = repositoryContext.Site.RootWeb;
                repositoryContext.Load(repositoryWeb, w => w.Url);
                repositoryContext.ExecuteQueryRetry();

                // Configure the XML SharePoint provider for the Infrastructural Site Collection
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(job.FileName,
                                                                              new SharePointConnector(repositoryContext, repositoryWeb.Url,
                                                                                                      PnPPartnerPackConstants.PnPProvisioningTemplates));

                ProvisioningTemplateCreationInformation ptci =
                    new ProvisioningTemplateCreationInformation(web);
                ptci.FileConnector                  = provider.Connector;
                ptci.IncludeAllTermGroups           = job.IncludeAllTermGroups;
                ptci.IncludeSearchConfiguration     = job.IncludeSearchConfiguration;
                ptci.IncludeSiteCollectionTermGroup = job.IncludeSiteCollectionTermGroup;
                ptci.IncludeSiteGroups              = job.IncludeSiteGroups;
                ptci.PersistBrandingFiles           = job.PersistComposedLookFiles;

                // We do intentionally remove taxonomies and search, which are not supported
                // in the AppOnly Authorization model
                // For further details, see the PnP Partner Pack documentation
                ptci.HandlersToProcess ^= Handlers.TermGroups;
                ptci.HandlersToProcess ^= Handlers.SearchSettings;

                // Extract the current template
                ProvisioningTemplate templateToSave = web.GetProvisioningTemplate(ptci);

                templateToSave.Description = job.Description;
                templateToSave.DisplayName = job.Title;

                // Save template image preview in folder
                Microsoft.SharePoint.Client.Folder templatesFolder = repositoryWeb.GetFolderByServerRelativeUrl(PnPPartnerPackConstants.PnPProvisioningTemplates);
                repositoryContext.Load(templatesFolder, f => f.ServerRelativeUrl, f => f.Name);
                repositoryContext.ExecuteQueryRetry();

                // If there is a preview image
                if (job.TemplateImageFile != null)
                {
                    // Determine the preview image file name
                    String previewImageFileName = job.FileName.ToLower().Replace(".pnp", "_preview.png");

                    // Save the preview image inside the Open XML package
                    provider.Connector.SaveFileStream(previewImageFileName, job.TemplateImageFile.ToStream());

                    // And store URL in the XML file
                    templateToSave.ImagePreviewUrl = String.Format("{0}{1}/{2}/{3}/{4}",
                                                                   repositoryWeb.Url.ToLower().StartsWith("https") ? "pnps" : "pnp",
                                                                   repositoryWeb.Url.Substring(repositoryWeb.Url.IndexOf("://")),
                                                                   templatesFolder.Name, job.FileName, previewImageFileName);
                }

                // And save it on the file system
                provider.SaveAs(templateToSave, job.FileName.ToLower().Replace(".pnp", ".xml"));

                Microsoft.SharePoint.Client.File templateFile = templatesFolder.GetFile(job.FileName);
                ListItem item = templateFile.ListItemAllFields;

                item[PnPPartnerPackConstants.ContentTypeIdField]               = PnPPartnerPackConstants.PnPProvisioningTemplateContentTypeId;
                item[PnPPartnerPackConstants.TitleField]                       = job.Title;
                item[PnPPartnerPackConstants.PnPProvisioningTemplateScope]     = job.Scope.ToString();
                item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl] = job.SourceSiteUrl;

                item.Update();

                repositoryContext.ExecuteQueryRetry();
            }
        }
        public PnPFileInfo GetPnPTemplateFileFromSite(CreatePnPTemplateRequest request)
        {
            var pnpPackageInfo = new PnPFileInfo();

            try
            {
                using (var context = TokenHelper.GetClientContextWithAccessToken(request.SiteUrl, request.AccessToken))
                {
                    var web = context.Web;
                    context.Load(web, w => w.Title, w => w.ServerRelativeUrl, w => w.Url);
                    context.ExecuteQuery();

                    var siteUrl = new Uri(request.SiteUrl);

                    var pnpFileName = "";

                    if (string.IsNullOrEmpty(request.PnpPackageName))
                    {
                        pnpFileName = BuildPnPPackageName(siteUrl);
                    }
                    else
                    {
                        pnpFileName = request.PnpPackageName;
                        if (pnpFileName.ToLower().EndsWith(".pnp"))
                        {
                            pnpFileName = pnpFileName.Substring(0, pnpFileName.Length - 4);
                        }
                    }
                    var pnpTemplatePath = HostingEnvironment.MapPath($"~/{TemplateFolder}");

                    var ptci = new ProvisioningTemplateCreationInformation(context.Web);
                    var fileSystemConnector = new FileSystemConnector(pnpTemplatePath, "");

                    ptci.PersistBrandingFiles          = true;
                    ptci.PersistPublishingFiles        = true;
                    ptci.PersistMultiLanguageResources = true;
                    ptci.FileConnector = new OpenXMLConnector($"{pnpFileName}.pnp", fileSystemConnector);

                    ptci.ProgressDelegate = delegate(String message, Int32 progress, Int32 total)
                    {
                        Console.WriteLine(@"{0:00}/{1:00} - {2}", progress, total, message);
                    };
                    ProvisioningTemplate template = new ProvisioningTemplate();
                    try
                    {
                        template = web.GetProvisioningTemplate(ptci);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("PnP engine failed to extract template. Error: {0}", ex.Message);
                    }

                    try
                    {
                        PageProvisionManager pageProvisionManager = new PageProvisionManager();
                        var pagesTemplate = pageProvisionManager.Extract(context, ptci);
                        foreach (var theFile in pagesTemplate.Files)
                        {
                            var existingFile =
                                template.Files.FirstOrDefault(
                                    f => f.Src.Equals(theFile.Src, StringComparison.InvariantCultureIgnoreCase));
                            if (existingFile == null)
                            {
                                template.Files.Add(theFile);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to extract Pages. Error: {0}", ex.Message);
                    }
                    if (web.IsSubSite())
                    {
                        try
                        {
                            var siteColumnsTemplate = new SiteColumnProvisionManager().Extract(web, ptci);
                            foreach (var col in siteColumnsTemplate.SiteFields)
                            {
                                if (!template.SiteFields.Contains(col))
                                {
                                    template.SiteFields.Add(col);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Failed to extract Site Columns. Error: {0}", ex.Message);
                        }
                        try
                        {
                            var siteCTTemplate = new ContentTypeProvisionManager().Extract(web, ptci);
                            foreach (var ct in siteCTTemplate.ContentTypes)
                            {
                                if (!template.ContentTypes.Contains(ct))
                                {
                                    template.ContentTypes.Add(ct);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Failed to extract Site Content Types. Error: {0}", ex.Message);
                        }
                    }

                    XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider((OpenXMLConnector)ptci.FileConnector);
                    provider.SaveAs(template, $"{pnpFileName}.xml");
                    string fileLocation = $"{pnpTemplatePath}\\{pnpFileName}.pnp";
                    var    file         = new FileInfo(fileLocation);

                    fileStorageManager.SaveFile($"{TemplateFolder}\\{pnpFileName}.pnp", System.IO.File.ReadAllBytes(fileLocation));

                    pnpPackageInfo = new PnPFileInfo()
                    {
                        Name = $"{pnpFileName}.pnp",
                        Size = file.Length / 1024.0m
                    };
                    if (file.Exists)
                    {
                        file.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(pnpPackageInfo);
        }
Exemplo n.º 22
0
        protected override void ExecuteCmdlet()
        {
            if (!System.IO.Path.IsPathRooted(Path))
            {
                Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
            }

            var template = ReadSiteTemplate
                           .LoadSiteTemplateFromFile(Path,
                                                     TemplateProviderExtensions, (e) =>
            {
                WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null));
            });

            if (template == null)
            {
                throw new ApplicationException("Invalid template file!");
            }
            //We will remove a list if it's found so we can get the list

            ListInstance listInstance = template.Lists.Find(l => l.Title == List.Title);

            if (listInstance == null)
            {
                throw new ApplicationException("List does not exist in the template file!");
            }

            List spList = List.GetList(SelectedWeb);

            ClientContext.Load(spList, l => l.RootFolder, l => l.HasUniqueRoleAssignments);
            ClientContext.ExecuteQueryRetry();

            if (TokenizeUrls.IsPresent)
            {
                ClientContext.Load(ClientContext.Web, w => w.Url, w => w.ServerRelativeUrl, w => w.Id);
                ClientContext.Load(ClientContext.Site, s => s.Url, s => s.ServerRelativeUrl, s => s.Id);
                ClientContext.Load(ClientContext.Web.Lists, lists => lists.Include(l => l.Title, l => l.RootFolder.ServerRelativeUrl));
            }

            CamlQuery query = new CamlQuery();

            var viewFieldsStringBuilder = new StringBuilder();

            if (Fields != null)
            {
                viewFieldsStringBuilder.Append("<ViewFields>");
                foreach (var field in Fields)
                {
                    viewFieldsStringBuilder.AppendFormat("<FieldRef Name='{0}'/>", field);
                }
                viewFieldsStringBuilder.Append("</ViewFields>");
            }

            query.ViewXml = string.Format("<View>{0}{1}</View>", Query, viewFieldsStringBuilder);
            var listItems = spList.GetItems(query);

            ClientContext.Load(listItems, lI => lI.Include(l => l.HasUniqueRoleAssignments, l => l.ContentType.StringId));
            ClientContext.ExecuteQueryRetry();

            Microsoft.SharePoint.Client.FieldCollection fieldCollection = spList.Fields;
            ClientContext.Load(fieldCollection, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind, f => f.ReadOnlyField));
            ClientContext.ExecuteQueryRetry();

            var rows = new DataRowCollection(template);

            foreach (var listItem in listItems)
            {
                //Make sure we don't pull Folders.. Of course this won't work
                if (listItem.ServerObjectIsNull == false)
                {
                    ClientContext.Load(listItem);
                    ClientContext.ExecuteQueryRetry();
                    if (!(listItem.FileSystemObjectType == FileSystemObjectType.Folder))
                    {
                        DataRow row = new DataRow();
                        if (IncludeSecurity && listItem.HasUniqueRoleAssignments)
                        {
                            row.Security.ClearSubscopes      = true;
                            row.Security.CopyRoleAssignments = false;

                            var roleAssignments = listItem.RoleAssignments;
                            ClientContext.Load(roleAssignments);
                            ClientContext.ExecuteQueryRetry();

                            ClientContext.Load(roleAssignments, r => r.Include(a => a.Member.LoginName, a => a.Member, a => a.RoleDefinitionBindings));
                            ClientContext.ExecuteQueryRetry();

                            foreach (var roleAssignment in roleAssignments)
                            {
                                var principalName = roleAssignment.Member.LoginName;
                                var roleBindings  = roleAssignment.RoleDefinitionBindings;
                                foreach (var roleBinding in roleBindings)
                                {
                                    row.Security.RoleAssignments.Add(new PnP.Framework.Provisioning.Model.RoleAssignment()
                                    {
                                        Principal = principalName, RoleDefinition = roleBinding.Name
                                    });
                                }
                            }
                        }
                        if (Fields != null)
                        {
                            foreach (var fieldName in Fields)
                            {
                                Microsoft.SharePoint.Client.Field dataField = fieldCollection.FirstOrDefault(f => f.InternalName == fieldName);

                                if (dataField != null)
                                {
                                    var defaultFieldValue = GetFieldValueAsText(ClientContext.Web, listItem, dataField);
                                    if (TokenizeUrls.IsPresent)
                                    {
                                        defaultFieldValue = Tokenize(defaultFieldValue, ClientContext.Web, ClientContext.Site);
                                    }

                                    row.Values.Add(fieldName, defaultFieldValue);
                                }
                            }
                        }
                        else
                        {
                            //All fields are added except readonly fields and unsupported field type
                            var fieldsToExport = fieldCollection.AsEnumerable()
                                                 .Where(f => !f.ReadOnlyField && !_unsupportedFieldTypes.Contains(f.FieldTypeKind));
                            foreach (var field in fieldsToExport)
                            {
                                var fldKey = (from f in listItem.FieldValues.Keys where f == field.InternalName select f).FirstOrDefault();
                                if (!string.IsNullOrEmpty(fldKey))
                                {
                                    var fieldValue = GetFieldValueAsText(ClientContext.Web, listItem, field);
                                    if (TokenizeUrls.IsPresent)
                                    {
                                        fieldValue = Tokenize(fieldValue, ClientContext.Web, ClientContext.Site);
                                    }
                                    row.Values.Add(field.InternalName, fieldValue);
                                }
                            }
                        }

                        rows.Add(row);
                    }
                }
            }
            template.Lists.Remove(listInstance);
            listInstance.DataRows.AddRange(rows);
            template.Lists.Add(listInstance);

            var outFileName = System.IO.Path.GetFileName(Path);
            var outPath     = new FileInfo(Path).DirectoryName;

            var fileSystemConnector = new FileSystemConnector(outPath, "");
            var formatter           = XMLPnPSchemaFormatter.LatestFormatter;
            var extension           = new FileInfo(Path).Extension.ToLowerInvariant();

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(Path, fileSystemConnector));
                var templateFileName         = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(Path, "");
                provider.SaveAs(template, Path, formatter, TemplateProviderExtensions);
            }
        }
        protected override void ExecuteCmdlet()
        {
            if (!System.IO.Path.IsPathRooted(Path))
            {
                Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
            }
            // Load the template
            var template = ProvisioningHelper.LoadSiteTemplateFromFile(Path, TemplateProviderExtensions, (e) =>
            {
                WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null));
            });

            if (template == null)
            {
                throw new ApplicationException("Invalid template file.");
            }


            List spList = List.GetList(CurrentWeb);

            ClientContext.Load(spList, l => l.RootFolder, l => l.HasUniqueRoleAssignments);
            ClientContext.ExecuteQueryRetry();

            //We will remove a list if it's found so we can get the list
            ListInstance listInstance = template.Lists.Find(l => l.Title == spList.Title);

            if (listInstance == null)
            {
                throw new ApplicationException("List does not exist in the template file.");
            }


            Microsoft.SharePoint.Client.Folder listFolder = spList.RootFolder;
            ClientContext.Load(listFolder);
            ClientContext.ExecuteQueryRetry();

            IList <PnP.Framework.Provisioning.Model.Folder> folders = GetChildFolders(listFolder);

            template.Lists.Remove(listInstance);
            listInstance.Folders.AddRange(folders);
            template.Lists.Add(listInstance);

            // Determine the output file name and path
            var outFileName = System.IO.Path.GetFileName(Path);
            var outPath     = new FileInfo(Path).DirectoryName;

            var fileSystemConnector = new FileSystemConnector(outPath, "");
            var formatter           = XMLPnPSchemaFormatter.LatestFormatter;
            var extension           = new FileInfo(Path).Extension.ToLowerInvariant();

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(Path, fileSystemConnector));
                var templateFileName         = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(Path, "");
                provider.SaveAs(template, Path, formatter, TemplateProviderExtensions);
            }
        }