Пример #1
0
        protected override void ExecuteCmdlet()
        {
            var sitesProvisioned = new List <ProvisionedSite>();
            var configuration    = new ApplyConfiguration();

            if (ParameterSpecified(nameof(Configuration)))
            {
                configuration = Configuration.GetConfiguration(SessionState.Path.CurrentFileSystemLocation.Path);
            }


            configuration.SiteProvisionedDelegate = (title, url) =>
            {
                if (sitesProvisioned.FirstOrDefault(s => s.Url == url) == null)
                {
                    sitesProvisioned.Add(new ProvisionedSite()
                    {
                        Title = title, Url = url
                    });
                }
            };

            if (ParameterSpecified(nameof(Handlers)))
            {
                if (!Handlers.Has(Handlers.All))
                {
                    foreach (var enumValue in (Handlers[])Enum.GetValues(typeof(Handlers)))
                    {
                        if (Handlers.Has(enumValue))
                        {
                            if (enumValue == Handlers.TermGroups)
                            {
                                configuration.Handlers.Add(ConfigurationHandler.Taxonomy);
                            }
                            else if (enumValue == Handlers.PageContents)
                            {
                                configuration.Handlers.Add(ConfigurationHandler.Pages);
                            }
                            else if (Enum.TryParse <ConfigurationHandler>(enumValue.ToString(), out ConfigurationHandler configHandler))
                            {
                                configuration.Handlers.Add(configHandler);
                            }
                        }
                    }
                }
            }
            if (ParameterSpecified(nameof(ExcludeHandlers)))
            {
                foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers)))
                {
                    if (!ExcludeHandlers.Has(handler) && handler != Handlers.All)
                    {
                        if (handler == Handlers.TermGroups)
                        {
                            if (configuration.Handlers.Contains(ConfigurationHandler.Taxonomy))
                            {
                                configuration.Handlers.Remove(ConfigurationHandler.Taxonomy);
                            }
                            else if (Enum.TryParse <ConfigurationHandler>(handler.ToString(), out ConfigurationHandler configHandler))
                            {
                                if (configuration.Handlers.Contains(configHandler))
                                {
                                    configuration.Handlers.Remove(configHandler);
                                }
                            }
                        }
                    }
                }
            }

            if (ExtensibilityHandlers != null)
            {
                configuration.Extensibility.Handlers = ExtensibilityHandlers.ToList();
            }

            configuration.ProgressDelegate = (message, step, total) =>
            {
                if (message != null)
                {
                    var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));
                    progressRecord.Activity          = $"Applying template to tenant";
                    progressRecord.StatusDescription = message;
                    progressRecord.PercentComplete   = percentage;
                    progressRecord.RecordType        = ProgressRecordType.Processing;
                    WriteProgress(progressRecord);
                }
            };

            var warningsShown = new List <string>();

            configuration.MessagesDelegate = (message, type) =>
            {
                switch (type)
                {
                case ProvisioningMessageType.Warning:
                {
                    if (!warningsShown.Contains(message))
                    {
                        WriteWarning(message);
                        warningsShown.Add(message);
                    }
                    break;
                }

                case ProvisioningMessageType.Progress:
                {
                    if (message != null)
                    {
                        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          = string.IsNullOrEmpty(messageSplitted[0]) ? "-" : messageSplitted[0];
                                subProgressRecord.StatusDescription = string.IsNullOrEmpty(messageSplitted[1]) ? "-" : 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;
                }
                }
            };

            configuration.PropertyBag.OverwriteSystemValues           = OverwriteSystemPropertyBagValues;
            configuration.Lists.IgnoreDuplicateDataRowErrors          = IgnoreDuplicateDataRowErrors;
            configuration.Navigation.ClearNavigation                  = ClearNavigation;
            configuration.ContentTypes.ProvisionContentTypesToSubWebs = ProvisionContentTypesToSubWebs;
            configuration.Fields.ProvisionFieldsToSubWebs             = ProvisionFieldsToSubWebs;

            ProvisioningHierarchy hierarchyToApply = null;

            switch (ParameterSetName)
            {
            case ParameterSet_PATH:
            {
                hierarchyToApply = GetHierarchy();
                break;
            }

            case ParameterSet_OBJECT:
            {
                hierarchyToApply = Template;
                if (ResourceFolder != null)
                {
                    var fileSystemConnector = new FileSystemConnector(ResourceFolder, "");
                    hierarchyToApply.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);
                    var fileConnector = new FileSystemConnector(fileInfo.DirectoryName, "");
                    hierarchyToApply.Connector = fileConnector;
                }
                break;
            }
            }
            if (Parameters != null)
            {
                foreach (var parameter in Parameters.Keys)
                {
                    if (hierarchyToApply.Parameters.ContainsKey(parameter.ToString()))
                    {
                        hierarchyToApply.Parameters[parameter.ToString()] = Parameters[parameter].ToString();
                    }
                    else
                    {
                        hierarchyToApply.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString());
                    }
                }
            }
#if !ONPREMISES
            // check if consent is needed and in place
            var consentRequired = false;
            if (hierarchyToApply.Teams != null)
            {
                consentRequired = true;
            }
            if (hierarchyToApply.AzureActiveDirectory != null)
            {
                consentRequired = true;
            }
            if (consentRequired)
            {
                // try to retrieve an access token for the Microsoft Graph:

                var accessToken = PnPConnection.CurrentConnection.TryGetAccessToken(Enums.TokenAudience.MicrosoftGraph);
                if (accessToken == null)
                {
                    if (PnPConnection.CurrentConnection.PSCredential != null)
                    {
                        // Using normal credentials
                        accessToken = TokenHandler.AcquireToken("graph.microsoft.com", null);
                    }
                    if (accessToken == null)
                    {
                        throw new PSInvalidOperationException("Your template contains artifacts that require an access token. Please provide consent to the PnP Management Shell application first by executing: Connect-PnPOnline -Graph -LaunchBrowser");
                    }
                }
            }

            using (var provisioningContext = new PnPProvisioningContext((resource, scope) =>
            {
                if (resource.ToLower().StartsWith("https://"))
                {
                    var uri = new Uri(resource);
                    resource = uri.Authority;
                }
                // Get Azure AD Token
                if (PnPConnection.CurrentConnection != null)
                {
                    if (resource.Equals("graph.microsoft.com", StringComparison.OrdinalIgnoreCase))
                    {
                        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...
                    throw new PSInvalidOperationException("Your template contains artifacts that require an access token. Please provide consent to the PnP Management Shell application first by executing: Connect-PnPOnline -Graph -LaunchBrowser");
                }
            }))
            {
#endif
            if (!string.IsNullOrEmpty(SequenceId))
            {
                Tenant.ApplyTenantTemplate(hierarchyToApply, SequenceId, configuration);
            }
            else
            {
                if (hierarchyToApply.Sequences.Count > 0)
                {
                    foreach (var sequence in hierarchyToApply.Sequences)
                    {
                        Tenant.ApplyTenantTemplate(hierarchyToApply, sequence.ID, configuration);
                    }
                }
                else
                {
                    Tenant.ApplyTenantTemplate(hierarchyToApply, null, configuration);
                }
            }
#if !ONPREMISES
        }
#endif
            WriteObject(sitesProvisioned, true);
        }
Пример #2
0
        private ProvisioningHierarchy ExtractTemplate(ExtractConfiguration configuration)
        {
            configuration.ProgressDelegate = (message, step, total) =>
            {
                var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));

                WriteProgress(new ProgressRecord(0, $"Extracting Tenant Template", message)
                {
                    PercentComplete = percentage
                });
                WriteProgress(new ProgressRecord(1, " ", " ")
                {
                    RecordType = ProgressRecordType.Completed
                });
            };
            configuration.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;
                }
                }
            };
            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);
                }
            }))
            {
                return(Tenant.GetTenantTemplate(configuration));
            }
        }
Пример #3
0
        private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName, ExtractConfiguration configuration)
        {
            SelectedWeb.EnsureProperty(w => w.Url);
            ProvisioningTemplateCreationInformation creationInformation = null;

            if (configuration != null)
            {
                creationInformation = configuration.ToCreationInformation(SelectedWeb);
            }
            else
            {
                creationInformation = new ProvisioningTemplateCreationInformation(SelectedWeb);
            }

            if (ParameterSpecified(nameof(Handlers)))
            {
                creationInformation.HandlersToProcess = Handlers;
            }
            if (ParameterSpecified(nameof(ExcludeHandlers)))
            {
                foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers)))
                {
                    if (!ExcludeHandlers.Has(handler) && handler != Handlers.All)
                    {
                        Handlers = Handlers | handler;
                    }
                }
                creationInformation.HandlersToProcess = Handlers;
            }

            var extension = "";

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

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

            if (extension == ".pnp")
            {
                creationInformation.FileConnector = new OpenXMLConnector(packageName, fileSystemConnector);
            }
            else
            {
                creationInformation.FileConnector = fileSystemConnector;
            }
#pragma warning disable 618
            if (ParameterSpecified(nameof(PersistBrandingFiles)))
            {
                creationInformation.PersistBrandingFiles = PersistBrandingFiles;
            }
#pragma warning restore 618
            creationInformation.PersistPublishingFiles       = PersistPublishingFiles;
            creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles;
            if (ParameterSpecified(nameof(IncludeSiteGroups)))
            {
                creationInformation.IncludeSiteGroups = IncludeSiteGroups;
            }
            creationInformation.IncludeTermGroupsSecurity  = IncludeTermGroupsSecurity;
            creationInformation.IncludeSearchConfiguration = IncludeSearchConfiguration;
            if (ParameterSpecified(nameof(IncludeHiddenLists)))
            {
                creationInformation.IncludeHiddenLists = IncludeHiddenLists;
            }
            if (ParameterSpecified(nameof(IncludeAllClientSidePages)))
            {
                creationInformation.IncludeAllClientSidePages = IncludeAllClientSidePages;
            }
            creationInformation.SkipVersionCheck = SkipVersionCheck;
            if (ParameterSpecified(nameof(ContentTypeGroups)) && ContentTypeGroups != null)
            {
                creationInformation.ContentTypeGroupsToInclude = ContentTypeGroups.ToList();
            }
            creationInformation.PersistMultiLanguageResources = PersistMultiLanguageResources;
            if (extension == ".pnp")
            {
                // if file is of pnp format, persist all files
                creationInformation.PersistBrandingFiles          = true;
                creationInformation.PersistPublishingFiles        = true;
                creationInformation.PersistMultiLanguageResources = true;
            }
            if (!string.IsNullOrEmpty(ResourceFilePrefix))
            {
                creationInformation.ResourceFilePrefix = ResourceFilePrefix;
            }
            else
            {
                if (Out != null)
                {
                    FileInfo fileInfo = new FileInfo(Out);
                    var      prefix   = fileInfo.Name;
                    // strip extension, if there is any
                    var indexOfLastDot = prefix.LastIndexOf(".", StringComparison.Ordinal);
                    if (indexOfLastDot > -1)
                    {
                        prefix = prefix.Substring(0, indexOfLastDot);
                    }
                    creationInformation.ResourceFilePrefix = prefix;
                }
            }
            if (ExtensibilityHandlers != null)
            {
                creationInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList();
            }

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

            creationInformation.ProgressDelegate = (message, step, total) =>
            {
                var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));

                WriteProgress(new ProgressRecord(0, $"Extracting Template from {SelectedWeb.Url}", message)
                {
                    PercentComplete = percentage
                });
                WriteProgress(new ProgressRecord(1, " ", " ")
                {
                    RecordType = ProgressRecordType.Completed
                });
            };
            creationInformation.MessagesDelegate = (message, type) =>
            {
                switch (type)
                {
                case ProvisioningMessageType.Warning:
                {
                    WriteWarning(message);
                    break;
                }

                case ProvisioningMessageType.Progress:
                {
                    var activity = message;
                    if (message.IndexOf("|") > -1)
                    {
                        var messageSplitted = message.Split('|');
                        if (messageSplitted.Length == 4)
                        {
                            var current = double.Parse(messageSplitted[2]);
                            var total   = double.Parse(messageSplitted[3]);
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.Activity          = messageSplitted[0];
                            subProgressRecord.StatusDescription = messageSplitted[1];
                            subProgressRecord.PercentComplete   = Convert.ToInt32((100 / total) * current);
                            WriteProgress(subProgressRecord);
                        }
                        else
                        {
                            subProgressRecord.Activity          = "Processing";
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.StatusDescription = activity;
                            subProgressRecord.PercentComplete   = 0;
                            WriteProgress(subProgressRecord);
                        }
                    }
                    else
                    {
                        subProgressRecord.Activity          = "Processing";
                        subProgressRecord.RecordType        = ProgressRecordType.Processing;
                        subProgressRecord.StatusDescription = activity;
                        subProgressRecord.PercentComplete   = 0;
                        WriteProgress(subProgressRecord);
                    }
                    break;
                }

                case ProvisioningMessageType.Completed:
                {
                    WriteProgress(new ProgressRecord(1, message, " ")
                        {
                            RecordType = ProgressRecordType.Completed
                        });
                    break;
                }
                }
            };

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

            if (ParameterSpecified(nameof(ExcludeContentTypesFromSyndication)))
            {
                creationInformation.IncludeContentTypesFromSyndication = !ExcludeContentTypesFromSyndication.ToBool();
            }

            if (ListsToExtract != null && ListsToExtract.Count > 0)
            {
                creationInformation.ListsToExtract.AddRange(ListsToExtract);
            }
            ProvisioningTemplate template = null;
            using (var provisioningContext = new PnPProvisioningContext((resource, scope) =>
            {
                // Get Azure AD Token
                if (PnPConnection.CurrentConnection != null)
                {
                    var graphAccessToken = PnPConnection.CurrentConnection.TryGetAccessToken(Enums.TokenAudience.MicrosoftGraph);
                    if (graphAccessToken != null)
                    {
                        // Authenticated using -Graph or using another way to retrieve the accesstoken with Connect-PnPOnline
                        return(Task.FromResult(graphAccessToken));
                    }
                }

                if (PnPConnection.CurrentConnection.PSCredential != null)
                {
                    // Using normal credentials
                    return(Task.FromResult(TokenHandler.AcquireToken(resource, null)));
                }
                else
                {
                    // No token...
                    return(null);
                }
            }))
            {
                template = SelectedWeb.GetProvisioningTemplate(creationInformation);
            }
            // Set metadata for template, if any
            SetTemplateMetadata(template, TemplateDisplayName, TemplateImagePreviewUrl, TemplateProperties);

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

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

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

                        WriteObject(reader.ReadToEnd());
                    }
                }
            }
            else
            {
                WriteObject(template);
            }
        }
        protected override void ExecuteCmdlet()
        {
            SelectedWeb.EnsureProperty(w => w.Url);
            ProvisioningTemplate provisioningTemplate;

            FileConnectorBase fileConnector;

            if (ParameterSpecified(nameof(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 (!System.IO.File.Exists(Path))
                    {
                        throw new FileNotFoundException($"File not found");
                    }
                    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 = FileUtilities.IsOpenOfficeFile(stream);
                XMLTemplateProvider provider;
                if (isOpenOfficeFile)
                {
                    var openXmlConnector = new OpenXMLConnector(templateFileName, fileConnector);
                    provider = new XMLOpenXMLTemplateProvider(openXmlConnector);
                    if (!String.IsNullOrEmpty(openXmlConnector.Info?.Properties?.TemplateFileName))
                    {
                        templateFileName = openXmlConnector.Info.Properties.TemplateFileName;
                    }
                    else
                    {
                        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");
                    }
                }

                if (ParameterSpecified(nameof(TemplateId)))
                {
                    provisioningTemplate = provider.GetTemplate(templateFileName, TemplateId, null, TemplateProviderExtensions);
                }
                else
                {
                    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
            {
                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(System.IO.Path.IsPathRooted(fileInfo.FullName) ? fileInfo.FullName : 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 (ParameterSpecified(nameof(Handlers)))
            {
                applyingInformation.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;
                    }
                }
                applyingInformation.HandlersToProcess = Handlers;
            }

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

            applyingInformation.ProgressDelegate = (message, step, total) =>
            {
                if (message != null)
                {
                    var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));
                    progressRecord.Activity          = $"Applying template to {SelectedWeb.Url}";
                    progressRecord.StatusDescription = message;
                    progressRecord.PercentComplete   = percentage;
                    progressRecord.RecordType        = ProgressRecordType.Processing;
                    WriteProgress(progressRecord);
                }
            };

            var warningsShown = new List <string>();

            applyingInformation.MessagesDelegate = (message, type) =>
            {
                switch (type)
                {
                case ProvisioningMessageType.Warning:
                {
                    if (!warningsShown.Contains(message))
                    {
                        WriteWarning(message);
                        warningsShown.Add(message);
                    }
                    break;
                }

                case ProvisioningMessageType.Progress:
                {
                    if (message != null)
                    {
                        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          = string.IsNullOrEmpty(messageSplitted[0]) ? "-" : messageSplitted[0];
                                subProgressRecord.StatusDescription = string.IsNullOrEmpty(messageSplitted[1]) ? "-" : 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;
                }
                }
            };

            applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues;
            applyingInformation.IgnoreDuplicateDataRowErrors     = IgnoreDuplicateDataRowErrors;
            applyingInformation.ClearNavigation = ClearNavigation;
            applyingInformation.ProvisionContentTypesToSubWebs = ProvisionContentTypesToSubWebs;
            applyingInformation.ProvisionFieldsToSubWebs       = ProvisionFieldsToSubWebs;

#if !ONPREMISES
            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);
                }
            }))
            {
#endif
            SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation);
#if !ONPREMISES
        }
#endif

            WriteProgress(new ProgressRecord(0, $"Applying template to {SelectedWeb.Url}", " ")
            {
                RecordType = ProgressRecordType.Completed
            });
        }
Пример #5
0
        protected override void ExecuteCmdlet()
        {
            if (MyInvocation.InvocationName.ToLower() == "apply-pnpprovisioninghierarchy")
            {
                WriteWarning("Apply-PnPProvisioningHierarchy has been deprecated. Use Apply-PnPTenantTemplate instead.");
            }

            var sitesProvisioned    = new List <ProvisionedSite>();
            var applyingInformation = new ProvisioningTemplateApplyingInformation();

            applyingInformation.SiteProvisionedDelegate = (title, url) =>
            {
                if (sitesProvisioned.FirstOrDefault(s => s.Url == url) == null)
                {
                    sitesProvisioned.Add(new ProvisionedSite()
                    {
                        Title = title, Url = url
                    });
                }
            };

            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) =>
            {
                if (message != null)
                {
                    var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));
                    progressRecord.Activity          = $"Applying template to tenant";
                    progressRecord.StatusDescription = message;
                    progressRecord.PercentComplete   = percentage;
                    progressRecord.RecordType        = ProgressRecordType.Processing;
                    WriteProgress(progressRecord);
                }
            };

            var warningsShown = new List <string>();

            applyingInformation.MessagesDelegate = (message, type) =>
            {
                switch (type)
                {
                case ProvisioningMessageType.Warning:
                {
                    if (!warningsShown.Contains(message))
                    {
                        WriteWarning(message);
                        warningsShown.Add(message);
                    }
                    break;
                }

                case ProvisioningMessageType.Progress:
                {
                    if (message != null)
                    {
                        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          = string.IsNullOrEmpty(messageSplitted[0]) ? "-" : messageSplitted[0];
                                subProgressRecord.StatusDescription = string.IsNullOrEmpty(messageSplitted[1]) ? "-" : 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;
                }
                }
            };

            applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues;
            applyingInformation.IgnoreDuplicateDataRowErrors     = IgnoreDuplicateDataRowErrors;
            applyingInformation.ClearNavigation = ClearNavigation;
            applyingInformation.ProvisionContentTypesToSubWebs = ProvisionContentTypesToSubWebs;
            applyingInformation.ProvisionFieldsToSubWebs       = ProvisionFieldsToSubWebs;

            ProvisioningHierarchy hierarchyToApply = null;

            switch (ParameterSetName)
            {
            case ParameterSet_PATH:
            {
                hierarchyToApply = GetHierarchy();
                break;
            }

            case ParameterSet_OBJECT:
            {
                hierarchyToApply = Template;
                if (ResourceFolder != null)
                {
                    var fileSystemConnector = new FileSystemConnector(ResourceFolder, "");
                    hierarchyToApply.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);
                    var fileConnector = new FileSystemConnector(fileInfo.DirectoryName, "");
                    hierarchyToApply.Connector = fileConnector;
                }
                break;
            }
            }
            if (Parameters != null)
            {
                foreach (var parameter in Parameters.Keys)
                {
                    if (hierarchyToApply.Parameters.ContainsKey(parameter.ToString()))
                    {
                        hierarchyToApply.Parameters[parameter.ToString()] = Parameters[parameter].ToString();
                    }
                    else
                    {
                        hierarchyToApply.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString());
                    }
                }
            }
#if !ONPREMISES
            using (var provisioningContext = new PnPProvisioningContext((resource, scope) =>
            {
                // Get Azure AD Token
                if (AccessToken != null)
                {
                    // Authenticated using -Graph or using another way to retrieve the accesstoken with Connect-PnPOnline
                    return(Task.FromResult(AccessToken));
                }
                else if (SPOnlineConnection.CurrentConnection.PSCredential != null)
                {
                    // Using normal credentials
                    return(Task.FromResult(TokenHandler.AcquireToken(resource, null)));
                }
                else
                {
                    // No token...
                    return(null);
                }
            }))
            {
#endif
            if (!string.IsNullOrEmpty(SequenceId))
            {
                Tenant.ApplyProvisionHierarchy(hierarchyToApply, SequenceId, applyingInformation);
            }
            else
            {
                if (hierarchyToApply.Sequences.Count > 0)
                {
                    foreach (var sequence in hierarchyToApply.Sequences)
                    {
                        Tenant.ApplyProvisionHierarchy(hierarchyToApply, sequence.ID, applyingInformation);
                    }
                }
                else
                {
                    Tenant.ApplyProvisionHierarchy(hierarchyToApply, null, applyingInformation);
                }
            }
#if !ONPREMISES
        }
#endif
            WriteObject(sitesProvisioned, true);
        }