private void UpdateTemplateOnWeb(Web targetWeb, RefreshSitesJob job) { targetWeb.EnsureProperty(w => w.Url); var infoJson = targetWeb.GetPropertyBagValueString(PnPPartnerPackConstants.PropertyBag_TemplateInfo, null); if (!String.IsNullOrEmpty(infoJson)) { Console.WriteLine($"Updating template for site: {targetWeb.Url}"); var info = JsonConvert.DeserializeObject<SiteTemplateInfo>(infoJson); // If we have the template info if (info != null && !String.IsNullOrEmpty(info.TemplateProviderType)) { ProvisioningTemplate template = null; // Try to retrieve the template var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[info.TemplateProviderType]; if (templatesProvider != null) { template = templatesProvider.GetProvisioningTemplate(info.TemplateUri); } // If we have the template if (template != null) { // Configure proper settings for the provisioning engine ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // Write provisioning steps on console log ptai.MessagesDelegate += delegate (string message, ProvisioningMessageType messageType) { Console.WriteLine("{0} - {1}", messageType, messageType); }; ptai.ProgressDelegate += delegate (string message, int step, int total) { Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message); }; // Exclude handlers not supported in App-Only ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings; // Configure template parameters if (info.TemplateParameters != null) { foreach (var key in info.TemplateParameters.Keys) { if (info.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = info.TemplateParameters[key]; } } } targetWeb.ApplyProvisioningTemplate(template, ptai); // Save the template information in the target site var updatedInfo = new SiteTemplateInfo() { TemplateProviderType = info.TemplateProviderType, TemplateUri = info.TemplateUri, TemplateParameters = template.Parameters, AppliedOn = DateTime.Now, }; var jsonInfo = JsonConvert.SerializeObject(updatedInfo); targetWeb.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo); Console.WriteLine($"Updated template on site: {targetWeb.Url}"); // Update (recursively) all the subwebs of the current web targetWeb.EnsureProperty(w => w.Webs); foreach (var subweb in targetWeb.Webs) { UpdateTemplateOnWeb(subweb, job); } } } } }
protected void btn_SetDefault_Click(object sender, System.EventArgs e) { LinkButton linkButton = (LinkButton)sender; int @int = WebUtils.GetInt(linkButton.CommandArgument); SiteTemplateInfo dataById = SiteTemplate.GetDataById(@int); if (dataById == null) { base.ShowAjaxMsg(this.UpdatePanel1, "没有找到模板,模板不存在或者已被删除"); } else if (!System.IO.Directory.Exists(base.Server.MapPath(dataById.TemplatePath))) { base.ShowAjaxMsg(this.UpdatePanel1, "找不到模板文件夹,请确认是否存在!"); } else if (SiteTemplate.SetDefaultTemplate(dataById.AutoID)) { CacheUtils.Del("JsonLeeCMS_CacheForSiteTemplate"); this.BindData(); PageBase.log.AddEvent(base.LoginAccount.AccountName, "设置模板[" + dataById.TemplateName + "]为当前默认使用的模板"); base.ShowAjaxMsg(this.UpdatePanel1, "设置默认模板成功"); } else { base.ShowAjaxMsg(this.UpdatePanel1, "设置默认模板失败"); } }
protected void lnk_Delete_Click(object sender, System.EventArgs e) { if (!base.IsAuthorizedOp(ActionType.Delete.ToString())) { base.ShowAjaxMsg(this.UpdatePanel1, "Không có thẩm quyền"); } else { int @int = WebUtils.GetInt((sender as LinkButton).CommandArgument); SiteTemplateInfo dataById = SiteTemplate.GetDataById(@int); if (dataById == null) { base.ShowAjaxMsg(this.UpdatePanel1, "没有找到此模板信息,模板不存在或者已删除"); } else if (PageBase.defaultTemplate.AutoID == dataById.AutoID) { base.ShowAjaxMsg(this.UpdatePanel1, "当前模板是默认模板,正在使用中,不可删除!"); } else if (SiteTemplate.Delete(@int)) { CacheUtils.Del("JsonLeeCMS_CacheForSiteTemplate"); this.BindData(); PageBase.log.AddEvent(base.LoginAccount.AccountName, "删除模板[" + dataById.TemplateName + "] thành công"); base.ShowAjaxMsg(this.UpdatePanel1, "Thao tác thành công"); } else { base.ShowAjaxMsg(this.UpdatePanel1, "Thao tác thất bại"); } } }
public async Task <ActionResult <BoolResult> > SaveData([FromBody] SaveRequest request) { if (!await _authManager.HasAppPermissionsAsync(MenuUtils.AppPermissions.SettingsSites)) { return(Unauthorized()); } var site = await _siteRepository.GetAsync(request.SiteId); var siteTemplatePath = _pathManager.GetSiteTemplatesPath(request.TemplateDir); var siteContentDirectoryPath = _pathManager.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteFiles.SiteTemplates.SiteContent); var caching = new CacheUtils(_cacheManager); var exportObject = new ExportObject(_pathManager, _databaseManager, caching, site); await exportObject.ExportSiteContentAsync(siteContentDirectoryPath, request.IsSaveContents, request.IsSaveAllChannels, request.CheckedChannelIds); await SiteTemplateManager.ExportSiteToSiteTemplateAsync(_pathManager, _databaseManager, caching, site, request.TemplateDir); var siteTemplateInfo = new SiteTemplateInfo { SiteTemplateName = request.TemplateName, PicFileName = string.Empty, WebSiteUrl = request.WebSiteUrl, Description = request.Description }; var xmlPath = _pathManager.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteFiles.SiteTemplates.FileMetadata); XmlUtils.SaveAsXml(siteTemplateInfo, xmlPath); return(new BoolResult { Value = true, }); }
protected void Page_Load(object sender, System.EventArgs e) { this.siteTemplate = SiteTemplate.GetCacheSiteTemplateByID(base.OpID); this.strFolderPath = WebUtils.GetQueryString("folder"); this.strFileName = WebUtils.GetQueryString("file"); this.strFolderPath = this.GetTempletPath(this.strFolderPath); if (!System.IO.Directory.Exists(this.strFolderPath)) { MessageUtils.ShowAndRedirect(this, "模板文件不存在", "TemplateList.aspx?Module=" + base.CurrentModuleCode + "&action=View"); } else { this.txtFolderPath.Text = this.strFolderPath; string templateFilePath = this.GetTemplateFilePath(); if (!base.IsPostBack && base.Action == ActionType.Modify.ToString()) { if (base.Action == ActionType.Modify.ToString() && !System.IO.File.Exists(templateFilePath)) { base.ShowMsgAndRdirect("模板文件不存在", "TemplateList.aspx?Module=" + base.CurrentModuleCode + "&action=View"); } else { this.FileContent.Text = FileUtils.ReadFileContent(templateFilePath); this.txtFileName.Text = this.strFileName.Substring(0, this.strFileName.LastIndexOf(".")); this.txtFileName.Enabled = false; ListItem listItem = this.ddlFileType.Items.FindByText(System.IO.Path.GetExtension(this.strFileName)); if (listItem != null) { listItem.Selected = true; } this.ddlFileType.Enabled = false; } } } }
public void BtnUploadImageFileNext_Click(object sender, EventArgs e) { BtnWelcomeNext.Visible = BtnSaveFilesNext.Visible = BtnSaveSiteContentsNext.Visible = BtnSaveSiteStylesNext.Visible = BtnUploadImageFileNext.Visible = PhWelcome.Visible = PhSaveFiles.Visible = PhSaveSiteContents.Visible = PhSaveSiteStyles.Visible = PhUploadImageFile.Visible = PhDone.Visible = false; string errorMessage; string samplePicPath; if (UploadImageFile(out errorMessage, out samplePicPath)) { var siteTemplateInfo = new SiteTemplateInfo { SiteTemplateName = TbSiteTemplateName.Text, PicFileName = samplePicPath, WebSiteUrl = TbWebSiteUrl.Text, Description = TbDescription.Text }; var siteTemplatePath = PathUtility.GetSiteTemplatesPath(TbSiteTemplateDir.Text); var xmlPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMetadata); Serializer.SaveAsXML(siteTemplateInfo, xmlPath); PhDone.Visible = true; } else { BtnUploadImageFileNext.Visible = PhUploadImageFile.Visible = true; FailMessage(errorMessage); } }
protected void Page_Load(object sender, System.EventArgs e) { this.siteTemplate = SiteTemplate.GetCacheSiteTemplateByID(base.OpID); if (this.siteTemplate == null) { MessageUtils.ShowAndRedirect(this, "没有找到模板信息", "TemplateList.aspx?Module=" + base.CurrentModuleCode + "&action=View"); } else { this.BindData(); } }
public static int Add(SiteTemplateInfo entity) { int result; if (entity == null) { result = 0; } else { result = BizBase.dbo.InsertModel <SiteTemplateInfo>(entity); } return(result); }
public void ExportMetadata(string siteTemplateName, string webSiteUrl, string description, string samplePicPath, string metadataPath) { var siteTemplateInfo = new SiteTemplateInfo { SiteTemplateName = siteTemplateName, PicFileName = samplePicPath, WebSiteUrl = webSiteUrl, Description = description }; var xmlPath = PathUtils.Combine(metadataPath, DirectoryUtils.SiteFiles.SiteTemplates.FileMetadata); XmlUtils.SaveAsXml(siteTemplateInfo, xmlPath); }
private void InitForModify() { SiteTemplateInfo dataById = SiteTemplate.GetDataById(base.OpID); if (dataById != null) { this.TextBox1.Text = dataById.TemplateName; this.TextBox2.Text = dataById.TemplatePath; this.TextBox3.Text = dataById.HomePage; this.TextBox4.Text = dataById.TemplateDesc; this.TextBox6.Text = dataById.Author; if (!string.IsNullOrEmpty(dataById.ShowPic)) { this.Image1.ImageUrl = dataById.ShowPic; this.previmg.Text = dataById.ShowPic; } } }
private void CreateSiteCollection(SiteCollectionProvisioningJob job) { Console.WriteLine("Creating Site Collection \"{0}\".", job.RelativeUrl); // Define the full Site Collection URL String siteUrl = String.Format("{0}{1}", PnPPartnerPackSettings.InfrastructureSiteUrl.Substring(0, PnPPartnerPackSettings.InfrastructureSiteUrl.IndexOf("sharepoint.com/") + 14), job.RelativeUrl); // Load the template from the source Templates Provider if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName)) { ProvisioningTemplate template = null; var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName]; if (templatesProvider != null) { template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl); } if (template != null) { using (var adminContext = PnPPartnerPackContextProvider.GetAppOnlyTenantLevelClientContext()) { adminContext.RequestTimeout = Timeout.Infinite; // Configure the Site Collection properties SiteEntity newSite = new SiteEntity(); newSite.Description = job.Description; newSite.Lcid = (uint)job.Language; newSite.Title = job.SiteTitle; newSite.Url = siteUrl; newSite.SiteOwnerLogin = job.PrimarySiteCollectionAdmin; newSite.StorageMaximumLevel = job.StorageMaximumLevel; newSite.StorageWarningLevel = job.StorageWarningLevel; // Use the BaseSiteTemplate of the template, if any, otherwise // fallback to the pre-configured site template (i.e. STS#0) newSite.Template = !String.IsNullOrEmpty(template.BaseSiteTemplate) ? template.BaseSiteTemplate : PnPPartnerPackSettings.DefaultSiteTemplate; newSite.TimeZoneId = job.TimeZone; newSite.UserCodeMaximumLevel = job.UserCodeMaximumLevel; newSite.UserCodeWarningLevel = job.UserCodeWarningLevel; // Create the Site Collection and wait for its creation (we're asynchronous) var tenant = new Tenant(adminContext); tenant.CreateSiteCollection(newSite, true, true); // TODO: Do we want to empty Recycle Bin? Site site = tenant.GetSiteByUrl(siteUrl); Web web = site.RootWeb; adminContext.Load(site, s => s.Url); adminContext.Load(web, w => w.Url); adminContext.ExecuteQueryRetry(); // Enable Secondary Site Collection Administrator if (!String.IsNullOrEmpty(job.SecondarySiteCollectionAdmin)) { Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(job.SecondarySiteCollectionAdmin); secondaryOwner.IsSiteAdmin = true; secondaryOwner.Update(); web.SiteUsers.AddUser(secondaryOwner); adminContext.ExecuteQueryRetry(); } Console.WriteLine("Site \"{0}\" created.", site.Url); // Check if external sharing has to be enabled if (job.ExternalSharingEnabled) { EnableExternalSharing(tenant, site); // Enable External Sharing Console.WriteLine("Enabled External Sharing for site \"{0}\".", site.Url); } } // Move to the context of the created Site Collection using (ClientContext clientContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl)) { clientContext.RequestTimeout = Timeout.Infinite; Site site = clientContext.Site; Web web = site.RootWeb; clientContext.Load(site, s => s.Url); clientContext.Load(web, w => w.Url); clientContext.ExecuteQueryRetry(); // Check if we need to enable PnP Partner Pack overrides if (job.PartnerPackExtensionsEnabled) { // Enable Responsive Design PnPPartnerPackUtilities.EnablePartnerPackOnSite(site.Url); Console.WriteLine("Enabled PnP Partner Pack Overrides on site \"{0}\".", site.Url); } // Check if the site has to be responsive if (job.ResponsiveDesignEnabled) { // Enable Responsive Design PnPPartnerPackUtilities.EnableResponsiveDesignOnSite(site.Url); Console.WriteLine("Enabled Responsive Design Template to site \"{0}\".", site.Url); } // Apply the Provisioning Template Console.WriteLine("Applying Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); // We do intentionally remove taxonomies, which are not supported // in the AppOnly Authorization model // For further details, see the PnP Partner Pack documentation ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // Write provisioning steps on console log ptai.MessagesDelegate += delegate(string message, ProvisioningMessageType messageType) { Console.WriteLine("{0} - {1}", messageType, messageType); }; ptai.ProgressDelegate += delegate(string message, int step, int total) { Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message); }; // Exclude handlers not supported in App-Only ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings; // Configure template parameters if (job.TemplateParameters != null) { foreach (var key in job.TemplateParameters.Keys) { if (job.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = job.TemplateParameters[key]; } } } // Fixup Title and Description if (template.WebSettings != null) { template.WebSettings.Title = job.SiteTitle; template.WebSettings.Description = job.Description; } // Apply the template to the target site web.ApplyProvisioningTemplate(template, ptai); // Save the template information in the target site var info = new SiteTemplateInfo() { TemplateProviderType = job.TemplatesProviderTypeName, TemplateUri = job.ProvisioningTemplateUrl, TemplateParameters = template.Parameters, AppliedOn = DateTime.Now, }; var jsonInfo = JsonConvert.SerializeObject(info); web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo); // Set site policy template if (!String.IsNullOrEmpty(job.SitePolicy)) { web.ApplySitePolicy(job.SitePolicy); } // Apply Tenant Branding, if requested if (job.ApplyTenantBranding) { var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings(); using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext( PnPPartnerPackSettings.InfrastructureSiteUrl)) { var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings); // Fixup Title and Description if (brandingTemplate != null) { if (brandingTemplate.WebSettings != null) { brandingTemplate.WebSettings.Title = job.SiteTitle; brandingTemplate.WebSettings.Description = job.Description; } // TO-DO: Need to handle exception here as there are multiple webs inside this where BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate); } } } Console.WriteLine("Applied Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); } } } }
public void BtnNext_Click(object sender, EventArgs e) { string errorMessage; if (CurrentWizardPanel == WizardPanel.Welcome) { if (SiteTemplateManager.Instance.IsSiteTemplateDirectoryExists(TbSiteTemplateDir.Text)) { LtlErrorMessage.Text = "站点模板保存失败,站点模板已存在!"; SetActivePlaceHolder(WizardPanel.OperatingError, PhOperatingError); } else { SetActivePlaceHolder(WizardPanel.SaveFiles, PhSaveFiles); } } else if (CurrentWizardPanel == WizardPanel.SaveFiles) { if (SaveFiles(out errorMessage)) { Body.AddAdminLog("保存站点模板", $"站点:{PublishmentSystemInfo.PublishmentSystemName}"); SetActivePlaceHolder(WizardPanel.SaveSiteContents, PhSaveSiteContents); } else { LtlErrorMessage.Text = errorMessage; SetActivePlaceHolder(WizardPanel.OperatingError, PhOperatingError); } } else if (CurrentWizardPanel == WizardPanel.SaveSiteContents) { if (SaveSiteContents(out errorMessage)) { SetActivePlaceHolder(WizardPanel.SaveSiteStyles, PhSaveSiteStyles); } else { LtlErrorMessage.Text = errorMessage; SetActivePlaceHolder(WizardPanel.OperatingError, PhOperatingError); } } else if (CurrentWizardPanel == WizardPanel.SaveSiteStyles) { if (SaveSiteStyles(out errorMessage)) { SetActivePlaceHolder(WizardPanel.UploadImageFile, PhUploadImageFile); } else { LtlErrorMessage.Text = errorMessage; SetActivePlaceHolder(WizardPanel.OperatingError, PhOperatingError); } } else if (CurrentWizardPanel == WizardPanel.UploadImageFile) { string samplePicPath; if (UploadImageFile(out errorMessage, out samplePicPath)) { try { var siteTemplateInfo = new SiteTemplateInfo { SiteTemplateName = TbSiteTemplateName.Text, PublishmentSystemType = EPublishmentSystemTypeUtils.GetValue(PublishmentSystemInfo.PublishmentSystemType), PicFileName = samplePicPath, WebSiteUrl = TbWebSiteUrl.Text, Description = TbDescription.Text }; var siteTemplatePath = PathUtility.GetSiteTemplatesPath(TbSiteTemplateDir.Text); var xmlPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMetadata); Serializer.SaveAsXML(siteTemplateInfo, xmlPath); SetActivePlaceHolder(WizardPanel.Done, PhDone); } catch (Exception ex) { LtlErrorMessage.Text = ex.Message; SetActivePlaceHolder(WizardPanel.OperatingError, PhOperatingError); } } else { LtlErrorMessage.Text = errorMessage; SetActivePlaceHolder(WizardPanel.OperatingError, PhOperatingError); } } }
protected void btnok_Click(object sender, System.EventArgs e) { if (base.Action.Equals(ActionType.Add.ToString()) && !base.IsAuthorizedOp(ActionType.Add.ToString())) { base.ShowMsg("Không có thẩm quyền"); } else if (base.Action.Equals(ActionType.Modify.ToString()) && !base.IsAuthorizedOp(ActionType.Modify.ToString())) { base.ShowMsg("Không có thẩm quyền"); } else { SiteTemplateInfo siteTemplateInfo = new SiteTemplateInfo(); if (base.IsEdit) { siteTemplateInfo = SiteTemplate.GetDataById(base.OpID); } siteTemplateInfo.TemplateName = WebUtils.GetString(this.TextBox1.Text); siteTemplateInfo.TemplatePath = WebUtils.GetString(this.TextBox2.Text); siteTemplateInfo.ShowPic = WebUtils.GetString(this.previmg.Text); siteTemplateInfo.HomePage = WebUtils.GetString(this.TextBox3.Text); siteTemplateInfo.TemplateDesc = WebUtils.GetString(this.TextBox4.Text); siteTemplateInfo.IsAudit = true; siteTemplateInfo.Author = WebUtils.GetString(this.TextBox6.Text); siteTemplateInfo.CopyRight = string.Empty; if (string.IsNullOrEmpty(siteTemplateInfo.TemplateName)) { base.ShowMsg("模板名称不能为空"); } else if (string.IsNullOrEmpty(siteTemplateInfo.TemplatePath)) { base.ShowMsg("模板路径不能为空"); } else { if (base.Action.Equals(ActionType.Add.ToString())) { siteTemplateInfo.AutoTimeStamp = System.DateTime.Now; if (SiteTemplate.Add(siteTemplateInfo) > 0) { CacheUtils.Del("JsonLeeCMS_CacheForSiteTemplate"); PageBase.log.AddEvent(base.LoginAccount.AccountName, "添加模板[" + siteTemplateInfo.TemplateName + "] thành công"); base.Response.Redirect(string.Concat(new object[] { "TemplateList.aspx?CatalogID=", base.CurrentCatalogID, "&Module=", base.CurrentModuleCode, "&action=View" })); } else { base.ShowMsg("添加模板失败"); } } if (base.Action.Equals(ActionType.Modify.ToString())) { if (SiteTemplate.Update(siteTemplateInfo)) { CacheUtils.Del("JsonLeeCMS_CacheForSiteTemplate"); PageBase.log.AddEvent(base.LoginAccount.AccountName, "修改模板[" + siteTemplateInfo.TemplateName + "] thành công"); base.Response.Redirect(string.Concat(new object[] { "TemplateList.aspx?CatalogID=", base.CurrentCatalogID, "&Module=", base.CurrentModuleCode, "&action=View" })); } else { base.ShowMsg("修改模板失败"); } } } } }
private void CreateSubSite(SubSiteProvisioningJob job) { // Determine the reference URLs and relative paths String subSiteUrl = job.RelativeUrl; String siteCollectionUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ParentSiteUrl); String parentSiteUrl = job.ParentSiteUrl; Console.WriteLine("Creating Site \"{0}\" as child Site of \"{1}\".", subSiteUrl, parentSiteUrl); using (ClientContext context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(parentSiteUrl)) { context.RequestTimeout = Timeout.Infinite; // Get a reference to the parent Web Web parentWeb = context.Web; // Load the template from the source Templates Provider if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName)) { ProvisioningTemplate template = null; var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName]; if (templatesProvider != null) { template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl); } if (template != null) { // Create the new sub site as a new child Web WebCreationInformation newWeb = new WebCreationInformation(); newWeb.Description = job.Description; newWeb.Language = job.Language; newWeb.Title = job.SiteTitle; newWeb.Url = subSiteUrl; newWeb.UseSamePermissionsAsParentSite = job.InheritPermissions; // Use the BaseSiteTemplate of the template, if any, otherwise // fallback to the pre-configured site template (i.e. STS#0) newWeb.WebTemplate = !String.IsNullOrEmpty(template.BaseSiteTemplate) ? template.BaseSiteTemplate : PnPPartnerPackSettings.DefaultSiteTemplate; Web web = parentWeb.Webs.Add(newWeb); context.ExecuteQueryRetry(); if (template.ExtensibilityHandlers.Any()) { // Clone Context pointing to Sub Site (needed for calling custom Extensibility Providers from the pnp template passing the right ClientContext) string newWeburl = web.EnsureProperty(w => w.Url); ClientContext webClientContext = context.Clone(newWeburl); web = webClientContext.Web; } // Create sub-web unique groups if (!job.InheritPermissions) { web.CreateDefaultAssociatedGroups(string.Empty, string.Empty, string.Empty); context.ExecuteQueryRetry(); } Console.WriteLine("Site \"{0}\" created.", subSiteUrl); // Apply the Provisioning Template Console.WriteLine("Applying Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); // We do intentionally remove taxonomies, which are not supported in the AppOnly Authorization model // For further details, see the PnP Partner Pack documentation ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // Write provisioning steps on console log ptai.MessagesDelegate = (message, type) => { switch (type) { case ProvisioningMessageType.Warning: { Console.WriteLine("{0} - {1}", type, message); break; } case ProvisioningMessageType.Progress: { var activity = message; if (message.IndexOf("|") > -1) { var messageSplitted = message.Split('|'); if (messageSplitted.Length == 4) { var status = messageSplitted[0]; var statusDescription = messageSplitted[1]; var current = double.Parse(messageSplitted[2]); var total = double.Parse(messageSplitted[3]); var percentage = Convert.ToInt32((100 / total) * current); Console.WriteLine("{0} - {1} - {2}", percentage, status, statusDescription); } else { Console.WriteLine(activity); } } else { Console.WriteLine(activity); } break; } case ProvisioningMessageType.Completed: { Console.WriteLine(type); break; } } }; ptai.ProgressDelegate = (message, step, total) => { var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step)); Console.WriteLine("{0:00}/{1:00} - {2} - {3}", step, total, percentage, message); }; // Exclude handlers not supported in App-Only ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings; // Configure template parameters foreach (var key in template.Parameters.Keys) { if (job.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = job.TemplateParameters[key]; } } // Fixup Title and Description if (template.WebSettings != null) { template.WebSettings.Title = job.SiteTitle; template.WebSettings.Description = job.Description; } // Replace existing structural navigation on target site if (template.Navigation != null && template.Navigation.CurrentNavigation != null && template.Navigation.CurrentNavigation.StructuralNavigation != null && (template.Navigation.CurrentNavigation.NavigationType == CurrentNavigationType.Structural || template.Navigation.CurrentNavigation.NavigationType == CurrentNavigationType.StructuralLocal)) { template.Navigation.CurrentNavigation.StructuralNavigation.RemoveExistingNodes = true; } // Replace existing Structural Global Navigation on target site if (template.Navigation != null && template.Navigation.GlobalNavigation != null && template.Navigation.GlobalNavigation.StructuralNavigation != null && template.Navigation.GlobalNavigation.NavigationType == GlobalNavigationType.Structural) { template.Navigation.GlobalNavigation.StructuralNavigation.RemoveExistingNodes = true; } // Apply the template to the target site web.ApplyProvisioningTemplate(template, ptai); // Save the template information in the target site var info = new SiteTemplateInfo() { TemplateProviderType = job.TemplatesProviderTypeName, TemplateUri = job.ProvisioningTemplateUrl, TemplateParameters = template.Parameters, AppliedOn = DateTime.Now, }; var jsonInfo = JsonConvert.SerializeObject(info); web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo); // Set site policy template if (!String.IsNullOrEmpty(job.SitePolicy)) { web.ApplySitePolicy(job.SitePolicy); } // Apply Tenant Branding, if requested if (job.ApplyTenantBranding) { var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings(); using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext( PnPPartnerPackSettings.InfrastructureSiteUrl)) { var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings); BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate); // Fixup Title and Description if (brandingTemplate != null) { if (brandingTemplate.WebSettings != null) { brandingTemplate.WebSettings.Title = job.SiteTitle; brandingTemplate.WebSettings.Description = job.Description; } // TO-DO: Need to handle exception here as there are multiple webs inside this where BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate); } } } Console.WriteLine("Applied Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); } } } }
private void CreateSubSite(SubSiteProvisioningJob job) { // Determine the reference URLs and relative paths String subSiteUrl = job.RelativeUrl; String siteCollectionUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ParentSiteUrl); String parentSiteUrl = job.ParentSiteUrl; Console.WriteLine("Creating Site \"{0}\" as child Site of \"{1}\".", subSiteUrl, parentSiteUrl); using (ClientContext context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(parentSiteUrl)) { context.RequestTimeout = Timeout.Infinite; // Get a reference to the parent Web Web parentWeb = context.Web; // Load the template from the source Templates Provider if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName)) { ProvisioningTemplate template = null; var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName]; if (templatesProvider != null) { template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl); } if (template != null) { // Create the new sub site as a new child Web WebCreationInformation newWeb = new WebCreationInformation(); newWeb.Description = job.Description; newWeb.Language = job.Language; newWeb.Title = job.SiteTitle; newWeb.Url = subSiteUrl; newWeb.UseSamePermissionsAsParentSite = job.InheritPermissions; // Use the BaseSiteTemplate of the template, if any, otherwise // fallback to the pre-configured site template (i.e. STS#0) newWeb.WebTemplate = !String.IsNullOrEmpty(template.BaseSiteTemplate) ? template.BaseSiteTemplate : PnPPartnerPackSettings.DefaultSiteTemplate; Web web = parentWeb.Webs.Add(newWeb); context.ExecuteQueryRetry(); Console.WriteLine("Site \"{0}\" created.", subSiteUrl); // Apply the Provisioning Template Console.WriteLine("Applying Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); // We do intentionally remove taxonomies, which are not supported in the AppOnly Authorization model // For further details, see the PnP Partner Pack documentation ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // Write provisioning steps on console log ptai.MessagesDelegate += delegate(string message, ProvisioningMessageType messageType) { Console.WriteLine("{0} - {1}", messageType, messageType); }; ptai.ProgressDelegate += delegate(string message, int step, int total) { Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message); }; // Exclude handlers not supported in App-Only ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings; // Configure template parameters foreach (var key in template.Parameters.Keys) { if (job.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = job.TemplateParameters[key]; } } // Fixup Title and Description template.WebSettings.Title = job.SiteTitle; template.WebSettings.Description = job.Description; // Apply the template to the target site web.ApplyProvisioningTemplate(template, ptai); // Save the template information in the target site var info = new SiteTemplateInfo() { TemplateProviderType = job.TemplatesProviderTypeName, TemplateUri = job.ProvisioningTemplateUrl, TemplateParameters = template.Parameters, AppliedOn = DateTime.Now, }; var jsonInfo = JsonConvert.SerializeObject(info); web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo); // Set site policy template if (!String.IsNullOrEmpty(job.SitePolicy)) { web.ApplySitePolicy(job.SitePolicy); } // Apply Tenant Branding, if requested if (job.ApplyTenantBranding) { var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings(); using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext( PnPPartnerPackSettings.InfrastructureSiteUrl)) { var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings); // Fixup Title and Description brandingTemplate.WebSettings.Title = job.SiteTitle; brandingTemplate.WebSettings.Description = job.Description; BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate); } } Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); } } } }
public static async Task <(bool Success, string name, string filePath)> PackageAsync(IPathManager pathManager, ICacheManager cacheManager, IDatabaseManager databaseManager, string directory, bool isOverride) { var site = await databaseManager.SiteRepository.GetSiteByDirectoryAsync(directory); var sitePath = await pathManager.GetSitePathAsync(site); if (site == null || !DirectoryUtils.IsDirectoryExists(sitePath)) { await WriteUtils.PrintErrorAsync($@"Invalid site directory path: ""{directory}"""); return(false, null, null); } var readme = string.Empty; Theme theme = null; var readmePath = PathUtils.Combine(sitePath, "README.md"); if (FileUtils.IsFileExists(readmePath)) { readme = FileUtils.ReadText(readmePath); var yaml = MarkdownUtils.GetYamlFrontMatter(readme); if (!string.IsNullOrEmpty(yaml)) { readme = MarkdownUtils.RemoveYamlFrontMatter(readme); theme = YamlUtils.Deserialize <Theme>(yaml); } } var writeReadme = false; if (theme == null || string.IsNullOrEmpty(theme.Name) || string.IsNullOrEmpty(theme.CoverUrl)) { writeReadme = true; theme = new Theme { Name = ReadUtils.GetString("name:"), CoverUrl = ReadUtils.GetString("cover image url:"), Summary = ReadUtils.GetString("repository url:"), Tags = ReadUtils.GetStringList("tags:"), ThumbUrls = ReadUtils.GetStringList("thumb image urls:"), Compatibilities = ReadUtils.GetStringList("compatibilities:"), Price = ReadUtils.GetYesNo("is free?") ? 0 : ReadUtils.GetDecimal("price:"), }; } if (writeReadme) { readme = @$ "--- {YamlUtils.Serialize(theme)} --- " + readme; FileUtils.WriteText(readmePath, readme); } var packageName = "T_" + theme.Name.Replace(" ", "_"); var packagePath = pathManager.GetSiteTemplatesPath(packageName); var fileName = packageName + ".zip"; var filePath = pathManager.GetSiteTemplatesPath(fileName); if (!isOverride && FileUtils.IsFileExists(filePath)) { return(true, theme.Name, filePath); } FileUtils.DeleteFileIfExists(filePath); DirectoryUtils.DeleteDirectoryIfExists(packagePath); await Console.Out.WriteLineAsync($"Theme name: {theme.Name}"); await Console.Out.WriteLineAsync($"Theme folder: {packagePath}"); await Console.Out.WriteLineAsync("Theme packaging..."); var caching = new CacheUtils(cacheManager); var manager = new SiteTemplateManager(pathManager, databaseManager, caching); if (manager.IsSiteTemplateDirectoryExists(packageName)) { manager.DeleteSiteTemplate(packageName); } var directoryNames = DirectoryUtils.GetDirectoryNames(sitePath); var directories = new List <string>(); var siteDirList = await databaseManager.SiteRepository.GetSiteDirsAsync(0); foreach (var directoryName in directoryNames) { var isSiteDirectory = false; if (site.Root) { foreach (var siteDir in siteDirList) { if (StringUtils.EqualsIgnoreCase(siteDir, directoryName)) { isSiteDirectory = true; } } } if (!isSiteDirectory && !pathManager.IsSystemDirectory(directoryName)) { directories.Add(directoryName); } } var files = DirectoryUtils.GetFileNames(sitePath); var exportObject = new ExportObject(pathManager, databaseManager, caching, site); await exportObject.ExportFilesToSiteAsync(packagePath, true, directories, files, true); var siteContentDirectoryPath = pathManager.GetSiteTemplateMetadataPath(packagePath, DirectoryUtils.SiteFiles.SiteTemplates.SiteContent); await exportObject.ExportSiteContentAsync(siteContentDirectoryPath, true, true, new List <int>()); await SiteTemplateManager.ExportSiteToSiteTemplateAsync(pathManager, databaseManager, caching, site, packageName); var siteTemplateInfo = new SiteTemplateInfo { SiteTemplateName = theme.Name, PicFileName = string.Empty, WebSiteUrl = string.Empty, Description = string.Empty }; var xmlPath = pathManager.GetSiteTemplateMetadataPath(packagePath, DirectoryUtils.SiteFiles.SiteTemplates.FileMetadata); XmlUtils.SaveAsXml(siteTemplateInfo, xmlPath); pathManager.CreateZip(filePath, packagePath); return(true, theme.Name, filePath); }
internal static void UpdateTemplateOnWeb(Web targetWeb, RefreshSitesJob job = null) { targetWeb.EnsureProperty(w => w.Url); var infoJson = targetWeb.GetPropertyBagValueString(PnPPartnerPackConstants.PropertyBag_TemplateInfo, null); if (!String.IsNullOrEmpty(infoJson)) { Console.WriteLine($"Updating template for site: {targetWeb.Url}"); var info = JsonConvert.DeserializeObject<SiteTemplateInfo>(infoJson); // If we have the template info if (info != null && !String.IsNullOrEmpty(info.TemplateProviderType)) { ProvisioningTemplate template = null; // Try to retrieve the template var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[info.TemplateProviderType]; if (templatesProvider != null) { template = templatesProvider.GetProvisioningTemplate(info.TemplateUri); } // If we have the template if (template != null) { // Configure proper settings for the provisioning engine ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // Write provisioning steps on console log ptai.MessagesDelegate += delegate (string message, ProvisioningMessageType messageType) { Console.WriteLine("{0} - {1}", messageType, messageType); }; ptai.ProgressDelegate += delegate (string message, int step, int total) { Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message); }; // Exclude handlers not supported in App-Only ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings; // Configure template parameters if (info.TemplateParameters != null) { foreach (var key in info.TemplateParameters.Keys) { if (info.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = info.TemplateParameters[key]; } } } targetWeb.ApplyProvisioningTemplate(template, ptai); // Save the template information in the target site var updatedInfo = new SiteTemplateInfo() { TemplateProviderType = info.TemplateProviderType, TemplateUri = info.TemplateUri, TemplateParameters = template.Parameters, AppliedOn = DateTime.Now, }; var jsonInfo = JsonConvert.SerializeObject(updatedInfo); targetWeb.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo); Console.WriteLine($"Updated template on site: {targetWeb.Url}"); // Update (recursively) all the subwebs of the current web targetWeb.EnsureProperty(w => w.Webs); foreach (var subweb in targetWeb.Webs) { UpdateTemplateOnWeb(subweb, job); } } } } }
private void CreateSubSite(SubSiteProvisioningJob job) { // Determine the reference URLs and relative paths String subSiteUrl = job.RelativeUrl; String siteCollectionUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ParentSiteUrl); String parentSiteUrl = job.ParentSiteUrl; Console.WriteLine("Creating Site \"{0}\" as child Site of \"{1}\".", subSiteUrl, parentSiteUrl); using (ClientContext context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(parentSiteUrl)) { context.RequestTimeout = Timeout.Infinite; // Get a reference to the parent Web Web parentWeb = context.Web; // Load the template from the source Templates Provider if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName)) { ProvisioningTemplate template = null; var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName]; if (templatesProvider != null) { template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl); } if (template != null) { // Create the new sub site as a new child Web WebCreationInformation newWeb = new WebCreationInformation(); newWeb.Description = job.Description; newWeb.Language = job.Language; newWeb.Title = job.SiteTitle; newWeb.Url = subSiteUrl; newWeb.UseSamePermissionsAsParentSite = job.InheritPermissions; // Use the BaseSiteTemplate of the template, if any, otherwise // fallback to the pre-configured site template (i.e. STS#0) newWeb.WebTemplate = !String.IsNullOrEmpty(template.BaseSiteTemplate) ? template.BaseSiteTemplate : PnPPartnerPackSettings.DefaultSiteTemplate; Web web = parentWeb.Webs.Add(newWeb); context.ExecuteQueryRetry(); Console.WriteLine("Site \"{0}\" created.", subSiteUrl); // Apply the Provisioning Template Console.WriteLine("Applying Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); // We do intentionally remove taxonomies, which are not supported in the AppOnly Authorization model // For further details, see the PnP Partner Pack documentation ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // Write provisioning steps on console log ptai.MessagesDelegate += delegate (string message, ProvisioningMessageType messageType) { Console.WriteLine("{0} - {1}", messageType, messageType); }; ptai.ProgressDelegate += delegate (string message, int step, int total) { Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message); }; // Exclude handlers not supported in App-Only ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings; // Configure template parameters foreach (var key in template.Parameters.Keys) { if (job.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = job.TemplateParameters[key]; } } // Fixup Title and Description template.WebSettings.Title = job.SiteTitle; template.WebSettings.Description = job.Description; // Apply the template to the target site web.ApplyProvisioningTemplate(template, ptai); // Save the template information in the target site var info = new SiteTemplateInfo() { TemplateProviderType = job.TemplatesProviderTypeName, TemplateUri = job.ProvisioningTemplateUrl, TemplateParameters = template.Parameters, AppliedOn = DateTime.Now, }; var jsonInfo = JsonConvert.SerializeObject(info); web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo); // Set site policy template if (!String.IsNullOrEmpty(job.SitePolicy)) { web.ApplySitePolicy(job.SitePolicy); } // Apply Tenant Branding, if requested if (job.ApplyTenantBranding) { var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings(); using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext( PnPPartnerPackSettings.InfrastructureSiteUrl)) { var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings); // Fixup Title and Description brandingTemplate.WebSettings.Title = job.SiteTitle; brandingTemplate.WebSettings.Description = job.Description; BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate); } } Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); } } } }
public static bool Update(SiteTemplateInfo entity) { return(entity != null && BizBase.dbo.UpdateModel <SiteTemplateInfo>(entity)); }
private void CreateSiteCollection(SiteCollectionProvisioningJob job) { Console.WriteLine("Creating Site Collection \"{0}\".", job.RelativeUrl); // Define the full Site Collection URL String siteUrl = String.Format("{0}{1}", PnPPartnerPackSettings.InfrastructureSiteUrl.Substring(0, PnPPartnerPackSettings.InfrastructureSiteUrl.IndexOf("sharepoint.com/") + 14), job.RelativeUrl); // Load the template from the source Templates Provider if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName)) { ProvisioningTemplate template = null; var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName]; if (templatesProvider != null) { template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl); } if (template != null) { using (var adminContext = PnPPartnerPackContextProvider.GetAppOnlyTenantLevelClientContext()) { adminContext.RequestTimeout = Timeout.Infinite; // Configure the Site Collection properties SiteEntity newSite = new SiteEntity(); newSite.Description = job.Description; newSite.Lcid = (uint)job.Language; newSite.Title = job.SiteTitle; newSite.Url = siteUrl; newSite.SiteOwnerLogin = job.PrimarySiteCollectionAdmin; newSite.StorageMaximumLevel = job.StorageMaximumLevel; newSite.StorageWarningLevel = job.StorageWarningLevel; // Use the BaseSiteTemplate of the template, if any, otherwise // fallback to the pre-configured site template (i.e. STS#0) newSite.Template = !String.IsNullOrEmpty(template.BaseSiteTemplate) ? template.BaseSiteTemplate : PnPPartnerPackSettings.DefaultSiteTemplate; newSite.TimeZoneId = job.TimeZone; newSite.UserCodeMaximumLevel = job.UserCodeMaximumLevel; newSite.UserCodeWarningLevel = job.UserCodeWarningLevel; // Create the Site Collection and wait for its creation (we're asynchronous) var tenant = new Tenant(adminContext); tenant.CreateSiteCollection(newSite, true, true); // TODO: Do we want to empty Recycle Bin? Site site = tenant.GetSiteByUrl(siteUrl); Web web = site.RootWeb; adminContext.Load(site, s => s.Url); adminContext.Load(web, w => w.Url); adminContext.ExecuteQueryRetry(); // Enable Secondary Site Collection Administrator if (!String.IsNullOrEmpty(job.SecondarySiteCollectionAdmin)) { Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(job.SecondarySiteCollectionAdmin); secondaryOwner.IsSiteAdmin = true; secondaryOwner.Update(); web.SiteUsers.AddUser(secondaryOwner); adminContext.ExecuteQueryRetry(); } Console.WriteLine("Site \"{0}\" created.", site.Url); // Check if external sharing has to be enabled if (job.ExternalSharingEnabled) { EnableExternalSharing(tenant, site); // Enable External Sharing Console.WriteLine("Enabled External Sharing for site \"{0}\".", site.Url); } } // Move to the context of the created Site Collection using (ClientContext clientContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl)) { clientContext.RequestTimeout = Timeout.Infinite; Site site = clientContext.Site; Web web = site.RootWeb; clientContext.Load(site, s => s.Url); clientContext.Load(web, w => w.Url); clientContext.ExecuteQueryRetry(); // Check if we need to enable PnP Partner Pack overrides if (job.PartnerPackExtensionsEnabled) { // Enable Responsive Design PnPPartnerPackUtilities.EnablePartnerPackOnSite(site.Url); Console.WriteLine("Enabled PnP Partner Pack Overrides on site \"{0}\".", site.Url); } // Check if the site has to be responsive if (job.ResponsiveDesignEnabled) { // Enable Responsive Design PnPPartnerPackUtilities.EnableResponsiveDesignOnSite(site.Url); Console.WriteLine("Enabled Responsive Design Template to site \"{0}\".", site.Url); } // Apply the Provisioning Template Console.WriteLine("Applying Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); // We do intentionally remove taxonomies, which are not supported // in the AppOnly Authorization model // For further details, see the PnP Partner Pack documentation ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // Write provisioning steps on console log ptai.MessagesDelegate += delegate (string message, ProvisioningMessageType messageType) { Console.WriteLine("{0} - {1}", messageType, messageType); }; ptai.ProgressDelegate += delegate (string message, int step, int total) { Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message); }; // Exclude handlers not supported in App-Only ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings; // Configure template parameters if (job.TemplateParameters != null) { foreach (var key in job.TemplateParameters.Keys) { if (job.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = job.TemplateParameters[key]; } } } // Fixup Title and Description if (template.WebSettings != null) { template.WebSettings.Title = job.SiteTitle; template.WebSettings.Description = job.Description; } // Apply the template to the target site web.ApplyProvisioningTemplate(template, ptai); // Save the template information in the target site var info = new SiteTemplateInfo() { TemplateProviderType = job.TemplatesProviderTypeName, TemplateUri = job.ProvisioningTemplateUrl, TemplateParameters = template.Parameters, AppliedOn = DateTime.Now, }; var jsonInfo = JsonConvert.SerializeObject(info); web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo); // Set site policy template if (!String.IsNullOrEmpty(job.SitePolicy)) { web.ApplySitePolicy(job.SitePolicy); } // Apply Tenant Branding, if requested if (job.ApplyTenantBranding) { var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings(); using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext( PnPPartnerPackSettings.InfrastructureSiteUrl)) { var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings); // Fixup Title and Description if (brandingTemplate != null) { if (brandingTemplate.WebSettings != null) { brandingTemplate.WebSettings.Title = job.SiteTitle; brandingTemplate.WebSettings.Description = job.Description; } // TO-DO: Need to handle exception here as there are multiple webs inside this where BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate); } } } Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); } } } }