Beispiel #1
1
        // ===========================================================================================================
        /// <summary>
        /// Applies the current template as an open XML ".pnp" package on the specified web
        /// </summary>
        /// <param name="web">The <b>Web</b> on which to apply the template</param>
        /// <param name="templateProvider">The <b>XMLTemplateProvider</b> that is mapped to the client's working directory</param>
        // ===========================================================================================================
        private void ApplyOpenXML(Web web, XMLTemplateProvider templateProvider)
        {
            logger.Info("Applying open XML package '{0}' from file '{1}'", this.Name, this.Path);

            // --------------------------------------------------
            // Formats the template's execution rendering
            // --------------------------------------------------
            ProvisioningTemplateApplyingInformation ptai = GetTemplateApplyInfo();

            // --------------------------------------------------
            // Replaces the regular provider by an OpenXml one
            // --------------------------------------------------
            string workingDirectory = templateProvider.Connector.Parameters[PARAMETER_CONNECTION_STRING].ToString();
            FileSystemConnector fileSystemConnector = new FileSystemConnector(workingDirectory, "");
            OpenXMLConnector openXmlConnector = new OpenXMLConnector(this.Path, fileSystemConnector);
            XMLTemplateProvider openXmlTemplateProvider = new XMLOpenXMLTemplateProvider(openXmlConnector);

            // --------------------------------------------------
            // Loops through all templates within the .pnp package
            // --------------------------------------------------
            List<ProvisioningTemplate> templates = openXmlTemplateProvider.GetTemplates();

            foreach (ProvisioningTemplate template in templates)
            {
                logger.Info("Applying template '{0}' from file '{1}'", template.Id, this.Path);

                // --------------------------------------------------
                // Applies the template 
                // --------------------------------------------------
                template.Connector = openXmlTemplateProvider.Connector;
                web.ApplyProvisioningTemplate(template, ptai);
            }
        }
        internal static ProvisioningTemplate GetTemplate(Guid templateId)
        {
            HttpContentHeaders headers = null;
            // Get the template via HTTP REST
            var templateStream = HttpHelper.MakeGetRequestForStreamWithResponseHeaders($"{BaseTemplateGalleryUrl}/api/DownloadTemplate?templateId={templateId}", "application/octet-stream", out headers);

            // If we have any result
            if (templateStream != null)
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateStream));
                var cd = new ContentDisposition(headers.ContentDisposition.ToString());
                var openXMLFileName = cd.FileName;

                // Determine the name of the XML file inside the PNP Open XML file
                var xmlTemplateFile = openXMLFileName.ToLower().Replace(".pnp", ".xml");

                // Get the template
                var result = provider.GetTemplate(xmlTemplateFile);
                result.Connector = provider.Connector;
                templateStream.Close();
                return result;

            }
            return null;
        }
        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);
            }
        }
        internal static ProvisioningTemplate LoadProvisioningTemplateFromFile(String templatePath, String sessionPath, ITemplateProviderExtension[] templateProviderExtensions)
        {
            // Prepare the File Connector
            FileConnectorBase fileConnector;
            string templateFileName = System.IO.Path.GetFileName(templatePath);

            // Prepare the template path
            if (!System.IO.Path.IsPathRooted(templatePath))
            {
                templatePath = System.IO.Path.Combine(sessionPath, templatePath);
            }
            var fileInfo = new FileInfo(templatePath);
            fileConnector = new FileSystemConnector(fileInfo.DirectoryName, "");

            ProvisioningTemplate provisioningTemplate;

            // Load the provisioning template file
            Stream stream = fileConnector.GetFileStream(templateFileName);
            var isOpenOfficeFile = ApplyProvisioningTemplate.IsOpenOfficeFile(stream);

            XMLTemplateProvider provider;
            if (isOpenOfficeFile)
            {
                provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector));
                templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";
            }
            else
            {
                provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", "");
            }

            provisioningTemplate = provider.GetTemplate(templateFileName, templateProviderExtensions);
            provisioningTemplate.Connector = provider.Connector;

            // Return the result
            return(provisioningTemplate);
        }
        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 ExecuteCmdlet()
        {
            SelectedWeb.EnsureProperty(w => w.Url);
            bool templateFromFileSystem = !Path.ToLower().StartsWith("http");
            FileConnectorBase fileConnector;
            string templateFileName = System.IO.Path.GetFileName(Path);
            if (templateFromFileSystem)
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                FileInfo fileInfo = new FileInfo(Path);
                fileConnector = new FileSystemConnector(fileInfo.DirectoryName, "");
            }
            else
            {
                Uri fileUri = new Uri(Path);
                var webUrl = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, fileUri);
                var templateContext = ClientContext.Clone(webUrl.ToString());

                string library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/');
                int idx = library.IndexOf("/");
                library = library.Substring(0, idx);
                fileConnector = new SharePointConnector(templateContext, templateContext.Url, library);
            }
            XMLTemplateProvider provider;
            ProvisioningTemplate provisioningTemplate;
            Stream stream = fileConnector.GetFileStream(templateFileName);
            var isOpenOfficeFile = ApplyProvisioningTemplate.IsOpenOfficeFile(stream);
            if (isOpenOfficeFile)
            {
                provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector));
                templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";
            }
            else
            {
                if (templateFromFileSystem)
                {
                    provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", "");
                }
                else
                {
                    throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library");
                }
            }
            provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions);

            if (provisioningTemplate == null) return;

            GetProvisioningTemplate.SetTemplateMetadata(provisioningTemplate, TemplateDisplayName, TemplateImagePreviewUrl, TemplateProperties);

            provider.SaveAs(provisioningTemplate, templateFileName, TemplateProviderExtensions);
        }
        public ActionResult GetTemplateImagePreviewFromPnP(String imagePreviewUri)
        {
            if (String.IsNullOrEmpty(imagePreviewUri))
            {
                throw new ArgumentNullException("imagePreviewUri");
            }

            // Recover the original protocol moniker
            var sourceUrl = imagePreviewUri.Replace("pnps://", "https://").Replace("pnp://", "http://");
            var imagePreviewFile = sourceUrl.Substring(sourceUrl.LastIndexOf("/") + 1);
            var pnpFileUrl = sourceUrl.Substring(0, sourceUrl.LastIndexOf("/"));
            var pnpFileName = pnpFileUrl.Substring(pnpFileUrl.LastIndexOf("/") + 1);
            var sourceSiteUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(pnpFileUrl);
            var sourceSiteFolder = pnpFileUrl.Substring(sourceSiteUrl.Length + 1, pnpFileUrl.LastIndexOf("/") - sourceSiteUrl.Length - 1);

            using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(sourceSiteUrl))
            {
                var repositoryWeb = repositoryContext.Web;
                repositoryWeb.EnsureProperty(w => w.Url);

                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(pnpFileName,
                    new SharePointConnector(repositoryContext, repositoryWeb.Url, sourceSiteFolder));

                var imageFileStream = provider.Connector.GetFileStream(imagePreviewFile);

                return (base.File(imageFileStream, "image/png"));
            }
        }
        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);
            }
        }
        protected override void ExecuteCmdlet()
        {
            SelectedWeb.EnsureProperty(w => w.Url);
            ProvisioningTemplate provisioningTemplate;

            FileConnectorBase fileConnector;
            if (MyInvocation.BoundParameters.ContainsKey("Path"))
            {
                bool templateFromFileSystem = !Path.ToLower().StartsWith("http");
                string templateFileName = System.IO.Path.GetFileName(Path);
                if (templateFromFileSystem)
                {
                    if (!System.IO.Path.IsPathRooted(Path))
                    {
                        Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                    }
                    if (!string.IsNullOrEmpty(ResourceFolder))
                    {
                        if (!System.IO.Path.IsPathRooted(ResourceFolder))
                        {
                            ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path,
                                ResourceFolder);
                        }
                    }
                    var fileInfo = new FileInfo(Path);
                    fileConnector = new FileSystemConnector(fileInfo.DirectoryName, "");
                }
                else
                {
                    Uri fileUri = new Uri(Path);
                    var webUrl = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, fileUri);
                    var templateContext = ClientContext.Clone(webUrl.ToString());

                    var library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/');
                    var idx = library.IndexOf("/", StringComparison.Ordinal);
                    library = library.Substring(0, idx);

                    // This syntax creates a SharePoint connector regardless we have the -InputInstance argument or not
                    fileConnector = new SharePointConnector(templateContext, templateContext.Url, library);
                }

            // If we don't have the -InputInstance parameter, we load the template from the source connector

                Stream stream = fileConnector.GetFileStream(templateFileName);
                var isOpenOfficeFile = IsOpenOfficeFile(stream);
                XMLTemplateProvider provider;
                if (isOpenOfficeFile)
                {
                    provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector));
                    templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";
                }
                else
                {
                    if (templateFromFileSystem)
                    {
                        provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", "");
                    }
                    else
                    {
                        throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library");
                    }
                }
                provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions);

                if (provisioningTemplate == null)
                {
                    // If we don't have the template, raise an error and exit
                    WriteError(new ErrorRecord(new Exception("The -Path parameter targets an invalid repository or template object."), "WRONG_PATH", ErrorCategory.SyntaxError, null));
                    return;
                }

                if (isOpenOfficeFile)
                {
                    provisioningTemplate.Connector = provider.Connector;
                }
                else
                {
                    if (ResourceFolder != null)
                    {
                        var fileSystemConnector = new FileSystemConnector(ResourceFolder, "");
                        provisioningTemplate.Connector = fileSystemConnector;
                    }
                    else
                    {
                        provisioningTemplate.Connector = provider.Connector;
                    }
                }
            }

            else
            {
                if (MyInvocation.BoundParameters.ContainsKey("GalleryTemplateId"))
                {
                    provisioningTemplate = GalleryHelper.GetTemplate(GalleryTemplateId);
                }
                else
                {
                    provisioningTemplate = InputInstance;
                }
                if (ResourceFolder != null)
                {
                    var fileSystemConnector = new FileSystemConnector(ResourceFolder, "");
                    provisioningTemplate.Connector = fileSystemConnector;
                }
                else
                {
                    if (Path != null)
                    {
                        if (!System.IO.Path.IsPathRooted(Path))
                        {
                            Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                        }
                    }
                    else
                    {
                        Path = SessionState.Path.CurrentFileSystemLocation.Path;
                    }
                    var fileInfo = new FileInfo(Path);
                    fileConnector = new FileSystemConnector(fileInfo.DirectoryName, "");
                    provisioningTemplate.Connector = fileConnector;
                }
            }

            if (Parameters != null)
            {
                foreach (var parameter in Parameters.Keys)
                {
                    if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString()))
                    {
                        provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString();
                    }
                    else
                    {
                        provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString());
                    }
                }
            }

            var applyingInformation = new ProvisioningTemplateApplyingInformation();

            if (MyInvocation.BoundParameters.ContainsKey("Handlers"))
            {
                applyingInformation.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;
                    }
                }
                applyingInformation.HandlersToProcess = Handlers;
            }

                if (ExtensibilityHandlers != null)
                {
                    applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList();
                }

                applyingInformation.ProgressDelegate = (message, step, total) =>
                {
                    WriteProgress(new ProgressRecord(0, $"Applying template to {SelectedWeb.Url}", message) { PercentComplete = (100 / total) * step });
                };

            applyingInformation.MessagesDelegate = (message, type) =>
            {
                if (type == ProvisioningMessageType.Warning)
                {
                    WriteWarning(message);
                }
            };

            applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues;
            SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation);

            WriteProgress(new ProgressRecord(0, $"Applying template to {SelectedWeb.Url}", " ") { RecordType = ProgressRecordType.Completed });
        }
        internal static void SaveTemplate(Guid templateId, string path, Func<string, bool> overWriteFileAction  = null, Action<string> itemSavedAction = null)
        {
            HttpContentHeaders headers = null;
            // Get the template via HTTP REST
            var templateStream =
                HttpHelper.MakeGetRequestForStreamWithResponseHeaders(
                    $"{BaseTemplateGalleryUrl}/api/DownloadTemplate?templateId={templateId}", "application/octet-stream",
                    out headers);

            // If we have any result
            if (templateStream != null)
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateStream));
                var cd = new ContentDisposition(headers.ContentDisposition.ToString());
                var openXMLFileName = cd.FileName;

                if (path != null)
                {
                    if (System.IO.Directory.Exists(path))
                    {
                        var fileName = System.IO.Path.Combine(path, openXMLFileName);
                        bool doSave = false;
                        if (System.IO.File.Exists(fileName))
                        {
                            if (overWriteFileAction != null)
                            {
                                doSave = overWriteFileAction(fileName);
                            }
                            else
                            {
                                doSave = true;
                            }
                        }
                        else
                        {
                            doSave = true;
                        }
                        if (doSave)
                        {
                            // Save the template to the path
                            using (var fileStream = System.IO.File.Create(fileName))
                            {
                                templateStream.Seek(0, SeekOrigin.Begin);
                                templateStream.CopyTo(fileStream);
                            }
                            itemSavedAction?.Invoke(fileName);
                        }
                    }
                }
                else
                {
                    // Determine the name of the XML file inside the PNP Open XML file
                    var xmlTemplateFile = openXMLFileName.ToLower().Replace(".pnp", ".xml");

                    // Get the template
                    var result = provider.GetTemplate(xmlTemplateFile);
                    result.Connector = provider.Connector;
                    templateStream.Close();
                }
            }
        }
        protected override void ExecuteCmdlet()
        {
            SelectedWeb.EnsureProperty(w => w.Url);
            bool templateFromFileSystem = !Path.ToLower().StartsWith("http");
            FileConnectorBase fileConnector;
            string templateFileName = System.IO.Path.GetFileName(Path);
            if (templateFromFileSystem)
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                if (!string.IsNullOrEmpty(ResourceFolder))
                {
                    if (!System.IO.Path.IsPathRooted(ResourceFolder))
                    {
                        ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path,
                            ResourceFolder);
                    }
                }
                FileInfo fileInfo = new FileInfo(Path);
                fileConnector = new FileSystemConnector(fileInfo.DirectoryName, "");
            }
            else
            {
                Uri fileUri = new Uri(Path);
                var webUrl = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(this.ClientContext, fileUri);
                var templateContext = this.ClientContext.Clone(webUrl.ToString());

                string library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/');
                int idx = library.IndexOf("/");
                library = library.Substring(0, idx);
                fileConnector = new SharePointConnector(templateContext, templateContext.Url, library);
            }
            XMLTemplateProvider provider = null;
            ProvisioningTemplate provisioningTemplate = null;
            Stream stream = fileConnector.GetFileStream(templateFileName);
            var isOpenOfficeFile = IsOpenOfficeFile(stream);
            if (isOpenOfficeFile)
            {
                provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector));
                templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".")) + ".xml";
            }
            else
            {
                if (templateFromFileSystem)
                {
                    provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", "");
                }
                else
                {
                    throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library");
                }
            }
            provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions);

            if (provisioningTemplate == null) return;

            if (isOpenOfficeFile)
            {
                provisioningTemplate.Connector = provider.Connector;
            }
            else
            {
                if (ResourceFolder != null)
                {
                    var fileSystemConnector = new FileSystemConnector(ResourceFolder, "");
                    provisioningTemplate.Connector = fileSystemConnector;
                }
                else
                {
                    provisioningTemplate.Connector = provider.Connector;
                }
            }

            if (Parameters != null)
            {
                foreach (var parameter in Parameters.Keys)
                {
                    if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString()))
                    {
                        provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString();
                    }
                    else
                    {
                        provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString());
                    }
                }
            }

            var applyingInformation = new ProvisioningTemplateApplyingInformation();

            if (this.MyInvocation.BoundParameters.ContainsKey("Handlers"))
            {
                applyingInformation.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;
                    }
                }
                applyingInformation.HandlersToProcess = Handlers;
            }

                if (ExtensibilityHandlers != null)
                {
                    applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList<ExtensibilityHandler>();
                }

                applyingInformation.ProgressDelegate = (message, step, total) =>
                {
                    WriteProgress(new ProgressRecord(0, string.Format("Applying template to {0}", SelectedWeb.Url), message) { PercentComplete = (100 / total) * step });
                };

            applyingInformation.MessagesDelegate = (message, type) =>
            {
                if (type == ProvisioningMessageType.Warning)
                {
                    WriteWarning(message);
                }
            };

            applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues;
            SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation);
        }
        protected override void ExecuteCmdlet()
        {
            SelectedWeb.EnsureProperty(w => w.Url);

            if (!System.IO.Path.IsPathRooted(Path))
            {
                Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
            }
            if (!string.IsNullOrEmpty(ResourceFolder))
            {
                if (!System.IO.Path.IsPathRooted(ResourceFolder))
                {
                    ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, ResourceFolder);
                }
            }

            FileInfo fileInfo = new FileInfo(Path);

            XMLTemplateProvider provider = null;
            ProvisioningTemplate provisioningTemplate = null;
            var isOpenOfficeFile = IsOpenOfficeFile(Path);
            if (isOpenOfficeFile)
            {
                var fileSystemconnector = new FileSystemConnector(fileInfo.DirectoryName, "");
                provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(fileInfo.Name, fileSystemconnector));
                var fileName = fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf(".")) + ".xml";
                provisioningTemplate = provider.GetTemplate(fileName);
            }
            else
            {
                provider = new XMLFileSystemTemplateProvider(fileInfo.DirectoryName, "");
                provisioningTemplate = provider.GetTemplate(fileInfo.Name);
            }

            if (provisioningTemplate != null)
            {
                if (isOpenOfficeFile)
                {
                    provisioningTemplate.Connector = provider.Connector;
                }
                else
                {
                    FileSystemConnector fileSystemConnector = null;
                    if (ResourceFolder != null)
                    {
                        fileSystemConnector = new FileSystemConnector(ResourceFolder, "");
                        provisioningTemplate.Connector = fileSystemConnector;
                    }
                    else
                    {
                        provisioningTemplate.Connector = provider.Connector;
                    }
                }

                if (Parameters != null)
                {
                    foreach (var parameter in Parameters.Keys)
                    {
                        if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString()))
                        {
                            provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString();
                        }
                        else
                        {
                            provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString());
                        }
                    }
                }

                var applyingInformation = new ProvisioningTemplateApplyingInformation();

                if (this.MyInvocation.BoundParameters.ContainsKey("Handlers"))
                {
                    applyingInformation.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;
                        }
                    }
                    applyingInformation.HandlersToProcess = Handlers;
                }

                if (ExtensibilityHandlers != null)
                {
                    applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList<ExtensibilityHandler>();
                }

                applyingInformation.ProgressDelegate = (message, step, total) =>
                {
                    WriteProgress(new ProgressRecord(0, string.Format("Applying template to {0}", SelectedWeb.Url), message) { PercentComplete = (100 / total) * step });
                };

                applyingInformation.MessagesDelegate = (message, type) =>
                {
                    if (type == ProvisioningMessageType.Warning)
                    {
                        WriteWarning(message);
                    }
                };

                applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues;
                SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation);
            }
        }
        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;
        }