protected override void ProcessRecord() { switch (ParameterSetName) { case ParameterSet_PATH: { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } WriteObject(ProvisioningHelper.LoadSiteTemplateFromFile(Path, TemplateProviderExtensions, (e) => { WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); })); break; } case ParameterSet_XML: { WriteObject(ProvisioningHelper.LoadSiteTemplateFromString(Xml, TemplateProviderExtensions, (e) => { WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); })); break; } } }
private async Task OnExecuteAsync() { HttpClient httpClient = await HttpClientHelper.GetHttpClientAsync(DigitalTwinsApiEndpoint, AadInstance, Tenant, DigitalTwinsResourceId, ClientId, ClientSecret); ProvisioningDescription provisioningDescription = ProvisioningHelper.LoadSmartHotelProvisioning(); await RemoveAllExistingDevicesAsync(httpClient, provisioningDescription); IReadOnlyCollection <Space> rootSpaces = await GetRootSpacesAsync(httpClient, provisioningDescription); await RemoveAllExistingResourcesAsync(httpClient, rootSpaces); await RemoveAllExistingRootSpacesAsync(httpClient, rootSpaces); if (RemoveEndpoints) { await RemoveAllExistingEndpoints(httpClient); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Press Enter to continue..."); Console.ReadLine(); }
public void Start(string fileName, DirectoryInfo directory, string options, string provisionResourceFolder = null) { ProvisioningTemplate template = null; using (var ctx = base.GetClientContext()) { if (provisionResourceFolder == null) { template = ProvisioningHelper.GetProvisioningTemplateFromResourcePath(fileName, directory); } else { template = ProvisioningHelper.GetProvisioningTemplateFromResourcePath(fileName, directory, provisionResourceFolder); } ProvisioningHelper.ReportOnTemplateStats(template); if (options.ToLower().IndexOf("quiet") < 0) { Console.WriteLine(""); Console.WriteLine("Continue (Y/N):"); string YesNo = Console.ReadLine(); if (YesNo.ToLower().IndexOf('n') >= 0) { return; } } ProvisioningHelper.ApplyCustomTemplateToSite(defaultForeground, ctx, template); } }
private bool RemoveItemFromTemplate(string projectItemFullPath, string projectItemKind, LoadedXMLProvisioningTemplate loadedTemplate) { if (loadedTemplate != null && loadedTemplate.Template != null) { var src = ProvisioningHelper.MakeRelativePath(projectItemFullPath, loadedTemplate.ResourcesPath); if (projectItemKind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder) { // Remove all files where src path starts with given folder path loadedTemplate.Template.Files.RemoveAll(f => f.Src.StartsWith(src, StringComparison.InvariantCultureIgnoreCase)); } else if (projectItemKind == EnvDTE.Constants.vsProjectItemKindPhysicalFile) { // Remove all files where src path equals item path loadedTemplate.Template.Files.RemoveAll(f => f.Src.Equals(src, StringComparison.InvariantCultureIgnoreCase)); } else { return(false); //terminate, wrong "kind" } LogService.Info("Item removed from template: " + src); return(true); } return(false); }
private void ProcessFiles(ProvisioningTemplate template, string templateFileName, FileConnectorBase fileSystemConnector) { var templateFile = ProvisioningHelper.LoadSiteTemplateFromFile(templateFileName, null, (e) => { WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); }); if (template.Tenant?.AppCatalog != null) { foreach (var app in template.Tenant.AppCatalog.Packages) { WriteObject($"Processing {app.Src}"); AddFile(app.Src, templateFile, fileSystemConnector); } } if (template.Tenant?.SiteScripts != null) { foreach (var siteScript in template.Tenant.SiteScripts) { WriteObject($"Processing {siteScript.JsonFilePath}"); AddFile(siteScript.JsonFilePath, templateFile, fileSystemConnector); } } if (template.Localizations != null && template.Localizations.Any()) { foreach (var location in template.Localizations) { WriteObject($"Processing {location.ResourceFile}"); AddFile(location.ResourceFile, templateFile, fileSystemConnector); } } if (template.WebSettings != null && !String.IsNullOrEmpty(template.WebSettings.SiteLogo)) { // is it a file? var isFile = false; using (var fileStream = fileSystemConnector.GetFileStream(template.WebSettings.SiteLogo)) { isFile = fileStream != null; } if (isFile) { WriteObject($"Processing {template.WebSettings.SiteLogo}"); AddFile(template.WebSettings.SiteLogo, templateFile, fileSystemConnector); } } if (template.Files.Any()) { foreach (var file in template.Files) { WriteObject($"Processing {file.Src}"); AddFile(file.Src, templateFile, fileSystemConnector); } } if (templateFile.Connector is ICommitableFileConnector) { ((ICommitableFileConnector)templateFile.Connector).Commit(); } }
public async Task <ActionResult> CompleteOperation(Guid subscriptionId) { string activatedBy = this.HttpContext.User.Identity.Name; AADAuthHelper.VerifyUserAccess(this.HttpContext, _logger, true); _logger.LogInformation($"Complete current operation for subscription {subscriptionId}. Operated by {activatedBy}."); if (!await _subscriptionService.ExistsAsync(subscriptionId)) { throw new LunaNotFoundUserException($"The specified subscription {subscriptionId} doesn't exist or you don't have permission to access it."); } Subscription sub = await _subscriptionService.GetAsync(subscriptionId); if (!ProvisioningHelper.IsErrorOrWarningProvisioningState(sub.ProvisioningStatus)) { throw new LunaConflictUserException($"Can not complete operation manually when provisioning in {sub.ProvisioningStatus} state."); } if (string.IsNullOrEmpty(activatedBy)) { throw new LunaBadRequestUserException("Need to specify the operation who is activating this subscription.", UserErrorCode.InvalidParameter); } return(Ok(await _provisioningService.UpdateOperationCompletedAsync(subscriptionId, activatedBy))); }
/// <summary> /// Get active provisions /// </summary> /// <returns>The active provisions</returns> public async Task <List <SubscriptionProvision> > GetInProgressProvisionsAsync() { List <SubscriptionProvision> statusList = new List <SubscriptionProvision>(); List <Subscription> subList = await _context.Subscriptions.ToListAsync(); foreach (var sub in subList) { if (sub.Status.Equals(nameof(FulfillmentState.Unsubscribed))) { Plan plan = await FindPlanById(sub.PlanId); if (sub.UnsubscribedTime.Value.AddDays(plan.DataRetentionInDays) > DateTime.UtcNow) { continue; } } else if (ProvisioningHelper.isFinalProvisioningState(sub.ProvisioningStatus)) { continue; } statusList.Add(new SubscriptionProvision { SubscriptionId = sub.SubscriptionId, ProvisioningStatus = sub.ProvisioningStatus, ProvisioningType = sub.ProvisioningType, RetryCount = sub.RetryCount, LastException = sub.LastException, SubscriptionStatus = sub.Status }); } return(statusList); }
private async Task OnExecuteAsync() { try { string fullUserObjectIdsFilePath = Path.GetFullPath(UserObjectIdsFile); string userAadObjectIdsString = await File.ReadAllTextAsync(fullUserObjectIdsFilePath); UserAadObjectIdsDescription userAadObjectIds = JsonConvert.DeserializeObject <UserAadObjectIdsDescription>(userAadObjectIdsString); if (!userAadObjectIds.AreRequiredValuesFilled()) { Console.WriteLine($"The {nameof( UserObjectIdsFile )} must have all the required properties filled." + " (Head Of Operations, Hotel Brand 1 Manager, Hotel 1 Manager, and Hotel 1 Employee)"); return; } HttpClient httpClient = await HttpClientHelper.GetHttpClientAsync(DigitalTwinsApiEndpoint, AadInstance, Tenant, DigitalTwinsResourceId, ClientId, ClientSecret); string fullPathToDigitalTwinsProvisioningFile = Path.GetFullPath(DigitalTwinsProvisioningFile); directoryContainingDigitalTwinsProvisioningFile = Path.GetDirectoryName(fullPathToDigitalTwinsProvisioningFile); Console.WriteLine("Loading the provisioning files..."); ProvisioningDescription provisioningDescription = ProvisioningHelper.LoadSmartHotelProvisioning(fullPathToDigitalTwinsProvisioningFile); Console.WriteLine("Successfully loaded provisioning files."); Console.WriteLine("Creating spaces and endpoints..."); await CreateSpacesAsync(httpClient, provisioningDescription.spaces, Guid.Empty, Guid.Empty, userAadObjectIds); Console.WriteLine(); Console.WriteLine(); Console.WriteLine($"Created {_spacesCreatedCount} spaces..."); Console.WriteLine(); Console.WriteLine(); await CreateEndpointsAsync(httpClient, provisioningDescription.endpoints); if (!string.IsNullOrEmpty(OutputFile)) { IDictionary <string, List <DeviceDescription> > allDevices = provisioningDescription.spaces.GetAllDeviceDescriptionsByDeviceIdPrefix(string.Empty); await File.WriteAllTextAsync(OutputFile, JsonConvert.SerializeObject(new SortedDictionary <string, List <DeviceDescription> >(allDevices))); } Console.WriteLine(); Console.WriteLine(); } catch (Exception ex) { Console.WriteLine($"Error occurred during Digital Twins provisioning: {ex}"); } }
public void Start(string outputFolder) { using (var ctx = base.GetClientContext()) { // GET the template from existing site and serialize it ProvisioningTemplate template = ProvisioningHelper.GenerateProvisioningTemplate(defaultForeground, ctx, outputFolder, "SiteExport_" + DateTimeStamp + ".xml"); } }
private async Task OnExecuteAsync() { try { if (RemoveDevices) { _actionMessage = "Removing"; _actionMessagePastTense = "Removed"; } _iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(IoTHubRegistryConnectionString); _registryManager = RegistryManager.CreateFromConnectionString(IoTHubRegistryConnectionString); Console.WriteLine("Loading the provisioning files..."); ProvisioningDescription provisioningDescription = ProvisioningHelper.LoadSmartHotelProvisioning(DigitalTwinsProvisioningFile); Console.WriteLine("Successfully loaded provisioning files."); if (!string.IsNullOrEmpty(OutputFile)) { var sw = Stopwatch.StartNew(); IDictionary <string, List <DeviceDescription> > allDevices = provisioningDescription.spaces.GetAllDeviceDescriptionsByDeviceIdPrefix(string.Empty); Console.WriteLine($"{_actionMessage} IoT Hub devices..."); Console.WriteLine(); Console.WriteLine(); IDictionary <string, string> deviceConnectionStringsByPrefix = await CreateIoTHubDevicesAndGetConnectionStringsAsync(allDevices); sw.Stop(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine($"{_actionMessagePastTense} IoT Hub devices successfully in {sw.Elapsed.TotalMinutes} minutes."); if (!RemoveDevices) { await File.WriteAllTextAsync(OutputFile, JsonConvert.SerializeObject( new SortedDictionary <string, string>(deviceConnectionStringsByPrefix))); } } Console.WriteLine(); Console.WriteLine(); } catch (Exception ex) { Console.WriteLine($"Error occurred during IoT Hub Device provisioning: {ex}"); } }
protected override IConfigurable PrepareDataObject() { TaskLogger.LogEnter(); this.DataObject = (TDataObject)((object)base.PrepareDataObject()); if (!base.HasErrors) { ADObjectId descendantId = base.CurrentOrgContainerId.GetDescendantId(ADProvisioningPolicy.RdnContainer); TDataObject[] array = this.ConfigurationSession.Find <TDataObject>(descendantId, QueryScope.SubTree, null, null, 2); if (array != null && array.Length != 0) { if (1 == array.Length) { Exception exception = new InvalidOperationException(Strings.ErrorOnlyOneProvisioningPolicyAllowed(array[0].Identity.ToString())); ErrorCategory category = ErrorCategory.InvalidOperation; TDataObject dataObject = this.DataObject; base.WriteError(exception, category, dataObject.Name); } else { Exception exception2 = new InvalidOperationException(Strings.ErrorMultipleProvisioningPolicyExist); ErrorCategory category2 = ErrorCategory.InvalidOperation; TDataObject dataObject2 = this.DataObject; base.WriteError(exception2, category2, dataObject2.Name); } } TDataObject dataObject3 = this.DataObject; ADObjectId descendantId2 = base.CurrentOrgContainerId.GetDescendantId(this.ContainerRdn); TDataObject dataObject4 = this.DataObject; dataObject3.SetId(descendantId2.GetChildId(dataObject4.Name)); TDataObject dataObject5 = this.DataObject; if (dataObject5.Scopes.Count != 0) { TDataObject dataObject6 = this.DataObject; dataObject6.Scopes.Clear(); } TDataObject dataObject7 = this.DataObject; dataObject7.Scopes.Add(base.CurrentOrgContainerId); TDataObject dataObject8 = this.DataObject; if (dataObject8.TargetObjects.Count != 0) { TDataObject dataObject9 = this.DataObject; dataObject9.TargetObjects.Clear(); } TDataObject dataObject10 = this.DataObject; foreach (Type poType in dataObject10.SupportedPresentationObjectTypes) { TDataObject dataObject11 = this.DataObject; dataObject11.TargetObjects.Add(ProvisioningHelper.GetProvisioningObjectTag(poType)); } } TaskLogger.LogExit(); return(this.DataObject); }
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 = ProvisioningHelper.LoadSiteTemplateFromFile(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); } } }
/// <summary> /// Create news pages, articles etc.. /// </summary> public void Start(string fileName, DirectoryInfo directory) { // get the list of groups sites var sites = Properties.Settings.Default.GroupSitesStage; foreach (var url in sites) { using (var ctx = GetClientContext(url)) { var template = ProvisioningHelper.GetProvisioningTemplateFromResourcePath(fileName, directory); ProvisioningHelper.ReportOnTemplateStats(template); ProvisioningHelper.ApplyCustomTemplateToSite(defaultForeground, ctx, template); } } }
/// <summary> /// Get warnings from subscription /// </summary> /// <param name="subscriptionId">Subscription id. Get all warnings if not specified</param> /// <returns>warnings</returns> public async Task <List <SubscriptionWarning> > GetWarnings(Guid?subscriptionId = null) { var subList = _context.Subscriptions.ToList().Where(s => ProvisioningHelper.IsErrorOrWarningProvisioningState(s.ProvisioningStatus) && (subscriptionId == null || s.SubscriptionId == subscriptionId)).ToList(); List <SubscriptionWarning> warnings = new List <SubscriptionWarning>(); foreach (var sub in subList) { warnings.Add(new SubscriptionWarning(sub.SubscriptionId, string.Format("Subscription in error state {0} since {1}.", sub.ProvisioningStatus, sub.LastUpdatedTime), string.Format("Last exception: {0}.", sub.LastException))); } return(warnings); }
private string GetFiles(XMLPnPSchemaVersion schema, string folder, string ctid) { ProvisioningTemplate template = new ProvisioningTemplate { Id = "FOLDEREXPORT", Security = null, Features = null, ComposedLook = null }; template.Files.AddRange(EnumerateFiles(folder, ctid, Properties)); var formatter = ProvisioningHelper.GetFormatter(schema); var outputStream = formatter.ToFormattedTemplate(template); StreamReader reader = new StreamReader(outputStream); return(reader.ReadToEnd()); }
private bool RenameTemplateItem(string projectItemFullPath, string projectItemKind, string oldName, LoadedXMLProvisioningTemplate loadedTemplate) { if (loadedTemplate != null && loadedTemplate.Template != null) { var src = ProvisioningHelper.MakeRelativePath(projectItemFullPath, loadedTemplate.ResourcesPath); if (projectItemKind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder) { var oldSrc = Path.Combine(src.Substring(0, src.TrimEnd('\\').LastIndexOf('\\')), oldName) + "\\"; // Remove all files where src path starts with given folder path var filesToRename = loadedTemplate.Template.Files.Where(f => f.Src.StartsWith(oldSrc, StringComparison.InvariantCultureIgnoreCase)); foreach (var file in filesToRename) { file.Src = Regex.Replace(file.Src, Regex.Escape(oldSrc), src, RegexOptions.IgnoreCase); } } else if (projectItemKind == EnvDTE.Constants.vsProjectItemKindPhysicalFile) { var oldSrc = Path.Combine(Path.GetDirectoryName(src), oldName); var file = loadedTemplate.Template.Files.Where( f => f.Src.Equals(oldSrc, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); if (file != null) { file.Src = src; } } else { return(false); //terminate, wrong item type } LogService.Info("Item renamed in template: " + src); return(true); } return(false); }
private async Task OnExecuteAsync() { HttpClient httpClient = await HttpClientHelper.GetHttpClientAsync(DigitalTwinsApiEndpoint, AadInstance, Tenant, DigitalTwinsResourceId, ClientId, ClientSecret); ProvisioningDescription provisioningDescription = ProvisioningHelper.LoadSmartHotelProvisioning(); await CreateSpacesAsync(httpClient, provisioningDescription.spaces, Guid.Empty, Guid.Empty); await CreateEndpointsAsync(httpClient, provisioningDescription.endpoints); if (!string.IsNullOrEmpty(OutputFile)) { IDictionary <string, List <DeviceDescription> > allDevices = provisioningDescription.spaces.GetAllDeviceDescriptions(); await File.WriteAllTextAsync(OutputFile, JsonConvert.SerializeObject(allDevices)); } Console.WriteLine(); Console.WriteLine(); }
private bool AddItemToTemplate(string projectItemFullPath, LoadedXMLProvisioningTemplate loadedTemplate) { if (loadedTemplate != null && loadedTemplate.Template != null) { // Item is PnP resource. var src = ProvisioningHelper.MakeRelativePath(projectItemFullPath, loadedTemplate.ResourcesPath); var targetFolder = String.Join("/", Path.GetDirectoryName(src).Split('\\')); loadedTemplate.Template.Files.Add(new OfficeDevPnP.Core.Framework.Provisioning.Model.File() { Src = src, Folder = targetFolder, Overwrite = true, Security = null }); LogService.Info("Item added to template: " + src); return(true); } return(false); }
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()); } } } } }
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); } }
static async Task MainAsync(string[] args) { Console.WriteLine("Getting device certificate..."); Parameters parameters = null; try { ValidateInput(args); parameters = ExtractParameters(args); if (parameters != null && !string.IsNullOrEmpty(parameters.DeviceId)) { string data = string.Empty; if (parameters.CreateDevice) { Device device = await ProvisioningHelper.AddDeviceAsync(parameters.DeviceId); if (device != null) { data = device.AuthenticationPrimaryKey; } } //in case no device creation has ben requested if (string.IsNullOrEmpty(data)) { data = await GetCertificateASync(parameters.DeviceId); } if (string.IsNullOrEmpty(parameters.CertificateDestinationPath)) { //display the response Console.WriteLine($"Device: {parameters.DeviceId}"); Console.WriteLine($"Certificate: {data}"); Console.ReadKey(); } else { //store the response in a file if (!string.IsNullOrEmpty(data)) { File.WriteAllText($"{parameters.CertificateDestinationPath}\\{parameters.DeviceId}.txt", data); } else { throw new Exception($"No key for device {parameters.DeviceId}"); } } } } catch (Exception ex) { if (parameters != null && !string.IsNullOrEmpty(parameters.CertificateDestinationPath)) { File.AppendAllText($"{parameters.CertificateDestinationPath}\\logs.txt", $"{Environment.NewLine}{DateTime.Now.ToString()}::ERROR::{ex.Message}"); } else { Console.WriteLine(ex.Message); Console.ReadKey(); } } }
static async Task <string> GetCertificateASync(string deviceId) { return(await ProvisioningHelper.GetCertificateFromProvisionnedDeviceAsync(deviceId)); }
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)) { 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 = ProvisioningHelper.GetFormatter(Schema); if (extension == ".pnp") { XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider( Out, fileSystemConnector); var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml"; provider.SaveAs(templateObject, templateFileName, formatter, TemplateProviderExtensions); ProcessFiles(templateObject, Out, fileSystemConnector); } else { XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(outPath, ""); provider.SaveAs(templateObject, Out, formatter, TemplateProviderExtensions); } }
private ProvisioningTemplateToolsConfiguration GetProvisioningTemplateToolsConfiguration(string projectFolderPath, bool createIfNotExists = false) { ProvisioningTemplateToolsConfiguration config = null; ProvisioningCredentials creds = null; var configFileCredsPath = Path.Combine(projectFolderPath, Resources.FileNameProvisioningUserCreds); var configFilePath = Path.Combine(projectFolderPath, Resources.FileNameProvisioningTemplate); var pnpTemplateFilePath = Path.Combine(projectFolderPath, Resources.DefaultFileNamePnPTemplate); try { //get the config from file config = Helpers.ProjectHelpers.GetConfigFile <ProvisioningTemplateToolsConfiguration>(configFilePath); creds = Helpers.ProjectHelpers.GetConfigFile <ProvisioningCredentials>(configFileCredsPath, false); if (config == null && createIfNotExists) { var resourcesFolder = Resources.DefaultResourcesRelativePath; EnsureResourcesFolder(projectFolderPath, resourcesFolder); config = ProvisioningHelper.GenerateDefaultProvisioningConfig(Resources.DefaultFileNamePnPTemplate, resourcesFolder); } config.EnsureInitialState(); //set the deserialized creds if (creds != null) { config.Deployment.Credentials = creds; } //set paths config.FilePath = configFilePath; config.ProjectPath = projectFolderPath; config.Deployment.Credentials.FilePath = configFileCredsPath; //ensure a default template exists if createIfNotExists is true if (config.Templates.Count == 0 && createIfNotExists) { var resourcesFolder = Resources.DefaultResourcesRelativePath; EnsureResourcesFolder(projectFolderPath, resourcesFolder); var tempConfig = ProvisioningHelper.GenerateDefaultProvisioningConfig(Resources.DefaultFileNamePnPTemplate, resourcesFolder); config.Templates = tempConfig.Templates; XmlHelpers.SerializeObject(config, configFilePath); //ensure pnp template files foreach (var t in config.Templates) { string templatePath = System.IO.Path.Combine(projectFolderPath, t.Path); if (!System.IO.File.Exists(templatePath)) { string resourcesPath = System.IO.Path.Combine(projectFolderPath, Resources.DefaultResourcesRelativePath); ProvisioningHelper.GenerateDefaultPnPTemplate(resourcesPath, templatePath); AddTemplateToProject(templatePath); } } } } catch (Exception ex) { ShowOutputPane(); LogService.Exception("Error in GetProvisioningTemplateToolsConfiguration", ex); } return(config); }
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); } }
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); } }
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); } }
protected override void ExecuteCmdlet() { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } var template = ProvisioningHelper.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 List spList = List.GetListOrThrow(nameof(List), CurrentWeb, l => l.RootFolder, l => l.HasUniqueRoleAssignments); ListInstance listInstance = template.Lists.Find(l => l.Title == spList.Title); if (listInstance == null) { throw new ApplicationException("List does not exist in the template file!"); } 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); 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 ProcessRecord() { 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!"); } if (this.ParameterSetName == parameterSet_REMOTEFILE) { CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); var sourceUri = new Uri(SourceUrl, UriKind.RelativeOrAbsolute); var serverRelativeUrl = sourceUri.IsAbsoluteUri ? sourceUri.AbsolutePath : SourceUrl.StartsWith("/", StringComparison.Ordinal) ? SourceUrl : CurrentWeb.ServerRelativeUrl.TrimEnd('/') + "/" + SourceUrl; var file = CurrentWeb.GetFileByServerRelativeUrl(serverRelativeUrl); var fileName = file.EnsureProperty(f => f.Name); var folderRelativeUrl = serverRelativeUrl.Substring(0, serverRelativeUrl.Length - fileName.Length - 1); var folderWebRelativeUrl = System.Net.WebUtility.UrlDecode(folderRelativeUrl.Substring(CurrentWeb.ServerRelativeUrl.TrimEnd('/').Length + 1)); if (ClientContext.HasPendingRequest) { ClientContext.ExecuteQueryRetry(); } try { var fi = CurrentWeb.GetFileByServerRelativeUrl(serverRelativeUrl); var fileStream = fi.OpenBinaryStream(); ClientContext.ExecuteQueryRetry(); using (var ms = fileStream.Value) { AddFileToTemplate(template, ms, folderWebRelativeUrl, fileName, folderWebRelativeUrl); } } catch (WebException exc) { WriteWarning($"Can't add file from url {serverRelativeUrl} : {exc}"); } } else { if (!System.IO.Path.IsPathRooted(Source)) { Source = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Source); } // Load the file and add it to the .PNP file using (var fs = System.IO.File.OpenRead(Source)) { Folder = Folder.Replace("\\", "/"); var fileName = Source.IndexOf("\\", StringComparison.Ordinal) > 0 ? Source.Substring(Source.LastIndexOf("\\") + 1) : Source; var container = !string.IsNullOrEmpty(Container) ? Container : string.Empty; AddFileToTemplate(template, fs, Folder, fileName, container); } } }