public void CanSerializeDomainObjectToMarkdown() { using (Stream _formattedTemplate = new FileStream(this._provisioningTemplatePath9, FileMode.Open, FileAccess.Read, FileShare.Read)) { ITemplateFormatter formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(this._provisioningTemplatePath9NamespaceURI); var _pt = formatter.ToProvisioningTemplate(_formattedTemplate); ITemplateFormatter mdFormatter = new MarkdownPnPFormatter(); var outputStream = mdFormatter.ToFormattedTemplate(_pt); Assert.IsTrue(mdFormatter.IsValid(outputStream)); } }
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 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)); }, azureEnvironment: PnPConnection.Current.AzureEnvironment)) { 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); } }
protected override void ExecuteCmdlet() { WriteWarning("This cmdlet is work in progress, the markdown report will improve/grow with later releases."); if (!Path.IsPathRooted(TemplatePath)) { TemplatePath = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, TemplatePath); } if (!File.Exists(TemplatePath)) { throw new PSArgumentException("File does not exist", nameof(TemplatePath)); } if (ShouldProcess($"Converts a PnP Site Template to markdown format")) { var process = false; var template = ProvisioningHelper.LoadSiteTemplateFromFile(TemplatePath, null, (exception) => { throw new PSInvalidOperationException("Invalid template", exception); }); ITemplateFormatter mdFormatter = new MarkdownPnPFormatter(); if (ParameterSpecified(nameof(Out))) { if (!Path.IsPathRooted(Out)) { Out = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Out); } if (File.Exists(Out)) { if (Force || ShouldContinue(string.Format(Resources.File0ExistsOverwrite, Out), Resources.Confirm)) { process = true; } } else { process = true; } if (process) { using (var outputStream = mdFormatter.ToFormattedTemplate(template)) { using (var fileStream = File.Create(Out)) { outputStream.Seek(0, SeekOrigin.Begin); outputStream.CopyTo(fileStream); fileStream.Close(); } } } } else { using (var outputStream = mdFormatter.ToFormattedTemplate(template)) { using (var reader = new StreamReader(outputStream)) { WriteObject(reader.ReadToEnd()); } } } } }