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);
            }
        }
        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);
            }
        }
        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);
            }
        }
        protected override void ProcessRecord()
        {
            // Determine the output file name and path
            string outFileName = System.IO.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 System.IO.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);
            }
        }
        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;
#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(".", 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) =>
            {
                WriteProgress(new ProgressRecord(0, $"Extracting Template from {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);

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

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