protected override void ExecuteCmdlet() { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } ClientObjectExtensions.EnsureProperty <Microsoft.SharePoint.Client.Web, string>(SelectedWeb, w => w.ServerRelativeUrl); var folder = FileFolderExtensions.EnsureFolder(SelectedWeb, SelectedWeb.RootFolder, Folder); var fileUrl = UrlUtility.Combine(folder.ServerRelativeUrl, System.IO.Path.GetFileName(Path)); // Check if the file exists if (Checkout) { try { var existingFile = SelectedWeb.GetFileByServerRelativeUrl(fileUrl); ClientObjectExtensions.EnsureProperty <File, bool>(existingFile, f => f.Exists); if (existingFile.Exists) { FileFolderExtensions.CheckOutFile(SelectedWeb, fileUrl); } } catch { // Swallow exception, file does not exist } } var file = folder.UploadFile(new FileInfo(Path).Name, Path, true); if (Values != null) { var item = file.ListItemAllFields; foreach (var key in Values.Keys) { item[key as string] = Values[key]; } item.Update(); ClientContext.ExecuteQueryRetry(); } if (Checkout) { FileFolderExtensions.CheckInFile(SelectedWeb, fileUrl, CheckinType.MajorCheckIn, CheckInComment); } if (Publish) { FileFolderExtensions.PublishFile(SelectedWeb, fileUrl, PublishComment); } if (Approve) { FileFolderExtensions.ApproveFile(SelectedWeb, fileUrl, ApproveComment); } WriteObject(file); }
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { var context = web.Context as ClientContext; web.EnsureProperties(w => w.ServerRelativeUrl, w => w.RootFolder.WelcomePage); // Check if this is not a noscript site as we're not allowed to update some properties bool isNoScriptSite = web.IsNoScriptSite(); foreach (var page in template.Pages) { var url = parser.ParseString(page.Url); if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower())) { url = UrlUtility.Combine(web.ServerRelativeUrl, url); } var exists = true; Microsoft.SharePoint.Client.File file = null; try { file = web.GetFileByServerRelativeUrl(url); web.Context.Load(file); web.Context.ExecuteQueryRetry(); } catch (ServerException ex) { if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException") { exists = false; } } if (exists) { if (page.Overwrite) { try { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0_, url); // determine url of current home page string welcomePageUrl = web.RootFolder.WelcomePage; string welcomePageServerRelativeUrl = welcomePageUrl != null ? UrlUtility.Combine(web.ServerRelativeUrl, web.RootFolder.WelcomePage) : null; bool overwriteWelcomePage = string.Equals(url, welcomePageServerRelativeUrl, StringComparison.InvariantCultureIgnoreCase); // temporarily reset home page so we can delete it if (overwriteWelcomePage) { web.SetHomePage(string.Empty); } file.DeleteObject(); web.Context.ExecuteQueryRetry(); web.AddWikiPageByUrl(url); if (page.Layout == WikiPageLayout.Custom) { web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url); } else { web.AddLayoutToWikiPage(page.Layout, url); } if (overwriteWelcomePage) { // restore welcome page to previous value web.SetHomePage(welcomePageUrl); } } catch (Exception ex) { scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace); } } } else { try { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0_, url); web.AddWikiPageByUrl(url); if (page.Layout == WikiPageLayout.Custom) { web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url); } else { web.AddLayoutToWikiPage(page.Layout, url); } } catch (Exception ex) { scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace); } } #pragma warning disable 618 if (page.WelcomePage) #pragma warning restore 618 { web.RootFolder.EnsureProperty(p => p.ServerRelativeUrl); var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length); web.SetHomePage(rootFolderRelativeUrl); } #if !SP2013 bool webPartsNeedLocalization = false; #endif if (page.WebParts != null && page.WebParts.Any()) { if (!isNoScriptSite) { var existingWebParts = web.GetWebParts(url); foreach (var webPart in page.WebParts) { if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == parser.ParseString(webPart.Title)) == null) { WebPartEntity wpEntity = new WebPartEntity { WebPartTitle = parser.ParseString(webPart.Title), WebPartXml = parser.ParseXmlStringWebpart(webPart.Contents.Trim(new[] { '\n', ' ' }), web) }; var wpd = web.AddWebPartToWikiPage(url, wpEntity, (int)webPart.Row, (int)webPart.Column, false); #if !SP2013 if (webPart.Title.ContainsResourceToken()) { // update data based on where it was added - needed in order to localize wp title wpd.EnsureProperties(w => w.ZoneId, w => w.WebPart, w => w.WebPart.Properties); webPart.Zone = wpd.ZoneId; webPart.Order = (uint)wpd.WebPart.ZoneIndex; webPartsNeedLocalization = true; } #endif } } // Remove any existing WebPartIdToken tokens in the parser that were added by other pages. They won't apply to this page, // and they'll cause issues if this page contains web parts with the same name as web parts on other pages. parser.Tokens.RemoveAll(t => t is WebPartIdToken); var allWebParts = web.GetWebParts(url); foreach (var webpart in allWebParts) { parser.AddToken(new WebPartIdToken(web, webpart.WebPart.Title, webpart.Id)); } } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_Pages_SkipAddingWebParts, page.Url); } } #if !SP2013 if (webPartsNeedLocalization) { page.LocalizeWebParts(web, parser, scope); } #endif file = web.GetFileByServerRelativeUrl(url); file.EnsureProperty(f => f.ListItemAllFields); if (page.Fields.Any()) { var item = file.ListItemAllFields; foreach (var fieldValue in page.Fields) { item[fieldValue.Key] = parser.ParseString(fieldValue.Value); } item.Update(); web.Context.ExecuteQueryRetry(); } if (page.Security != null && page.Security.RoleAssignments.Count != 0) { web.Context.Load(file.ListItemAllFields); web.Context.ExecuteQueryRetry(); file.ListItemAllFields.SetSecurity(parser, page.Security, WriteMessage); } } } return(parser); }
/// <summary> /// Process the metadata copying (as defined in the used page layout mapping) /// </summary> public void Transform() { if (this.pageLayoutMappingModel != null) { bool isDirty = false; bool listItemWasReloaded = false; string contentTypeId = null; // Set content type if (!string.IsNullOrEmpty(this.pageLayoutMappingModel.AssociatedContentType)) { contentTypeId = CacheManager.Instance.GetContentTypeId(this.page.PageListItem.ParentList, pageLayoutMappingModel.AssociatedContentType); if (!string.IsNullOrEmpty(contentTypeId)) { // Load the target page list item, needs to be loaded as it was previously saved and we need to avoid version conflicts this.targetClientContext.Load(this.page.PageListItem); this.targetClientContext.ExecuteQueryRetry(); listItemWasReloaded = true; this.page.PageListItem[Constants.ContentTypeIdField] = contentTypeId; this.page.PageListItem.UpdateOverwriteVersion(); isDirty = true; } } // Determine content type to use if (string.IsNullOrEmpty(contentTypeId)) { // grab the default content type contentTypeId = this.page.PageListItem[Constants.ContentTypeIdField].ToString(); } if (this.pageLayoutMappingModel.MetaData != null) { // Handle the taxonomy fields bool targetSitePagesLibraryLoaded = false; List targetSitePagesLibrary = null; foreach (var fieldToProcess in this.pageLayoutMappingModel.MetaData.Field) { // Process only fields which have a target field set... if (!string.IsNullOrEmpty(fieldToProcess.TargetFieldName)) { if (!listItemWasReloaded) { // Load the target page list item, needs to be loaded as it was previously saved and we need to avoid version conflicts this.targetClientContext.Load(this.page.PageListItem); this.targetClientContext.ExecuteQueryRetry(); listItemWasReloaded = true; } // Get information about this content type field var targetFieldData = CacheManager.Instance.GetPublishingContentTypeField(this.page.PageListItem.ParentList, contentTypeId, fieldToProcess.TargetFieldName); if (targetFieldData == null) { LogWarning($"{LogStrings.TransformCopyingMetaDataFieldSkipped} {fieldToProcess.TargetFieldName}", LogStrings.Heading_CopyingPageMetadata); } else { if (targetFieldData.FieldType == "TaxonomyFieldTypeMulti" || targetFieldData.FieldType == "TaxonomyFieldType") { if (!targetSitePagesLibraryLoaded) { var sitePagesServerRelativeUrl = UrlUtility.Combine(targetClientContext.Web.ServerRelativeUrl, "sitepages"); targetSitePagesLibrary = this.targetClientContext.Web.GetList(sitePagesServerRelativeUrl); this.targetClientContext.Web.Context.Load(targetSitePagesLibrary, l => l.Fields.IncludeWithDefaultProperties(f => f.Id, f => f.Title, f => f.Hidden, f => f.InternalName, f => f.DefaultValue, f => f.Required)); this.targetClientContext.ExecuteQueryRetry(); targetSitePagesLibraryLoaded = true; } switch (targetFieldData.FieldType) { case "TaxonomyFieldTypeMulti": { var taxFieldBeforeCast = targetSitePagesLibrary.Fields.Where(p => p.Id.Equals(targetFieldData.FieldId)).FirstOrDefault(); if (taxFieldBeforeCast != null) { var taxField = this.targetClientContext.CastTo <TaxonomyField>(taxFieldBeforeCast); if (this.publishingPageTransformationInformation.SourcePage.FieldExists(fieldToProcess.Name)) { if (this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name] is TaxonomyFieldValueCollection) { var valueCollectionToCopy = (this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name] as TaxonomyFieldValueCollection); var taxonomyFieldValueArray = valueCollectionToCopy.Select(taxonomyFieldValue => $"-1;#{taxonomyFieldValue.Label}|{taxonomyFieldValue.TermGuid}"); var valueCollection = new TaxonomyFieldValueCollection(this.targetClientContext, string.Join(";#", taxonomyFieldValueArray), taxField); taxField.SetFieldValueByValueCollection(this.page.PageListItem, valueCollection); isDirty = true; LogInfo($"{LogStrings.TransformCopyingMetaDataField} {targetFieldData.FieldName}", LogStrings.Heading_CopyingPageMetadata); } else if (this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name] is Dictionary <string, object> ) { var taxDictionaryList = (this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name] as Dictionary <string, object>); var valueCollectionToCopy = taxDictionaryList["_Child_Items_"] as Object[]; List <string> taxonomyFieldValueArray = new List <string>(); for (int i = 0; i < valueCollectionToCopy.Length; i++) { var taxDictionary = valueCollectionToCopy[i] as Dictionary <string, object>; taxonomyFieldValueArray.Add($"-1;#{taxDictionary["Label"].ToString()}|{taxDictionary["TermGuid"].ToString()}"); } if (valueCollectionToCopy.Length > 0) { var valueCollection = new TaxonomyFieldValueCollection(this.targetClientContext, string.Join(";#", taxonomyFieldValueArray), taxField); taxField.SetFieldValueByValueCollection(this.page.PageListItem, valueCollection); isDirty = true; LogInfo($"{LogStrings.TransformCopyingMetaDataField} {targetFieldData.FieldName}", LogStrings.Heading_CopyingPageMetadata); } else { // Publishing field was empty, so let's skip the metadata copy LogInfo(string.Format(LogStrings.TransformCopyingMetaDataTaxFieldEmpty, targetFieldData.FieldName), LogStrings.Heading_CopyingPageMetadata); } } else { // Publishing field was empty, so let's skip the metadata copy LogInfo(string.Format(LogStrings.TransformCopyingMetaDataTaxFieldEmpty, targetFieldData.FieldName), LogStrings.Heading_CopyingPageMetadata); } } else { // Log that field in page layout mapping was not found LogWarning(string.Format(LogStrings.Warning_FieldNotFoundInSourcePage, fieldToProcess.Name), LogStrings.Heading_CopyingPageMetadata); } } break; } case "TaxonomyFieldType": { var taxFieldBeforeCast = targetSitePagesLibrary.Fields.Where(p => p.Id.Equals(targetFieldData.FieldId)).FirstOrDefault(); if (taxFieldBeforeCast != null) { var taxField = this.targetClientContext.CastTo <TaxonomyField>(taxFieldBeforeCast); var taxValue = new TaxonomyFieldValue(); if (this.publishingPageTransformationInformation.SourcePage.FieldExists(fieldToProcess.Name)) { if (this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name] is TaxonomyFieldValue) { taxValue.Label = (this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name] as TaxonomyFieldValue).Label; taxValue.TermGuid = (this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name] as TaxonomyFieldValue).TermGuid; taxValue.WssId = -1; taxField.SetFieldValueByValue(this.page.PageListItem, taxValue); isDirty = true; LogInfo($"{LogStrings.TransformCopyingMetaDataField} {targetFieldData.FieldName}", LogStrings.Heading_CopyingPageMetadata); } else if (this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name] is Dictionary <string, object> ) { var taxDictionary = (this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name] as Dictionary <string, object>); taxValue.Label = taxDictionary["Label"].ToString(); taxValue.TermGuid = taxDictionary["TermGuid"].ToString(); taxValue.WssId = -1; taxField.SetFieldValueByValue(this.page.PageListItem, taxValue); isDirty = true; LogInfo($"{LogStrings.TransformCopyingMetaDataField} {targetFieldData.FieldName}", LogStrings.Heading_CopyingPageMetadata); } else { // Publishing field was empty, so let's skip the metadata copy LogInfo(string.Format(LogStrings.TransformCopyingMetaDataTaxFieldEmpty, targetFieldData.FieldName), LogStrings.Heading_CopyingPageMetadata); } } else { // Log that field in page layout mapping was not found LogWarning(string.Format(LogStrings.Warning_FieldNotFoundInSourcePage, fieldToProcess.Name), LogStrings.Heading_CopyingPageMetadata); } } break; } } } } } } // Persist changes if (isDirty) { this.page.PageListItem.UpdateOverwriteVersion(); targetClientContext.Load(this.page.PageListItem); targetClientContext.ExecuteQueryRetry(); isDirty = false; } string bannerImageUrl = null; // Copy the field metadata foreach (var fieldToProcess in this.pageLayoutMappingModel.MetaData.Field) { // check if the source field name attribute contains a delimiter value if (fieldToProcess.Name.Contains(";")) { // extract the array of field names to process, and trims each one string[] sourceFieldNames = fieldToProcess.Name.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray(); // sets the field name to the first "valid" entry fieldToProcess.Name = this.publishingPageTransformationInformation.GetFirstNonEmptyFieldName(sourceFieldNames); } // Process only fields which have a target field set... if (!string.IsNullOrEmpty(fieldToProcess.TargetFieldName)) { if (!listItemWasReloaded) { // Load the target page list item, needs to be loaded as it was previously saved and we need to avoid version conflicts this.targetClientContext.Load(this.page.PageListItem); this.targetClientContext.ExecuteQueryRetry(); listItemWasReloaded = true; } // Get information about this content type field var targetFieldData = CacheManager.Instance.GetPublishingContentTypeField(this.page.PageListItem.ParentList, contentTypeId, fieldToProcess.TargetFieldName); if (targetFieldData == null) { LogWarning($"{LogStrings.TransformCopyingMetaDataFieldSkipped} {fieldToProcess.TargetFieldName}", LogStrings.Heading_CopyingPageMetadata); } else { if (targetFieldData.FieldType != "TaxonomyFieldTypeMulti" && targetFieldData.FieldType != "TaxonomyFieldType") { if (this.publishingPageTransformationInformation.SourcePage.FieldExists(fieldToProcess.Name)) { object fieldValueToSet = null; if (!string.IsNullOrEmpty(fieldToProcess.Functions)) { // execute function var evaluatedField = this.functionProcessor.Process(fieldToProcess.Functions, fieldToProcess.Name, CastToPublishingFunctionProcessorFieldType(targetFieldData.FieldType)); if (!string.IsNullOrEmpty(evaluatedField.Item1)) { fieldValueToSet = evaluatedField.Item2; } } else { fieldValueToSet = this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name]; } if (fieldValueToSet != null) { if (targetFieldData.FieldType == "User" || targetFieldData.FieldType == "UserMulti") { if (fieldValueToSet is FieldUserValue) { // Publishing page transformation always goes cross site collection, so we'll need to lookup a user again // Important to use a cloned context to not mess up with the pending list item updates try { // Source User var fieldUser = (fieldValueToSet as FieldUserValue).LookupValue; // Mapped target user fieldUser = this.userTransformator.RemapPrincipal(this.sourceClientContext, (fieldValueToSet as FieldUserValue)); // Ensure user exists on target site var ensuredUserOnTarget = CacheManager.Instance.GetEnsuredUser(this.page.Context, fieldUser); if (ensuredUserOnTarget != null) { // Prep a new FieldUserValue object instance and update the list item var newUser = new FieldUserValue() { LookupId = ensuredUserOnTarget.Id }; this.page.PageListItem[targetFieldData.FieldName] = newUser; } else { // Clear target field - needed in overwrite scenarios this.page.PageListItem[targetFieldData.FieldName] = null; LogWarning(string.Format(LogStrings.Warning_UserIsNotMappedOrResolving, (fieldValueToSet as FieldUserValue).LookupValue, targetFieldData.FieldName), LogStrings.Heading_CopyingPageMetadata); } } catch (Exception ex) { LogWarning(string.Format(LogStrings.Warning_UserIsNotResolving, (fieldValueToSet as FieldUserValue).LookupValue, ex.Message), LogStrings.Heading_CopyingPageMetadata); } } else { List <FieldUserValue> userValues = new List <FieldUserValue>(); foreach (var currentUser in (fieldValueToSet as Array)) { try { // Source User var fieldUser = (currentUser as FieldUserValue).LookupValue; // Mapped target user fieldUser = this.userTransformator.RemapPrincipal(this.sourceClientContext, (currentUser as FieldUserValue)); // Ensure user exists on target site var ensuredUserOnTarget = CacheManager.Instance.GetEnsuredUser(this.page.Context, fieldUser); if (ensuredUserOnTarget != null) { // Prep a new FieldUserValue object instance var newUser = new FieldUserValue() { LookupId = ensuredUserOnTarget.Id }; userValues.Add(newUser); } else { LogWarning(string.Format(LogStrings.Warning_UserIsNotMappedOrResolving, (currentUser as FieldUserValue).LookupValue, targetFieldData.FieldName), LogStrings.Heading_CopyingPageMetadata); } } catch (Exception ex) { LogWarning(string.Format(LogStrings.Warning_UserIsNotResolving, (currentUser as FieldUserValue).LookupValue, ex.Message), LogStrings.Heading_CopyingPageMetadata); } } if (userValues.Count > 0) { this.page.PageListItem[targetFieldData.FieldName] = userValues.ToArray(); } else { // Clear target field - needed in overwrite scenarios this.page.PageListItem[targetFieldData.FieldName] = null; } } } else { this.page.PageListItem[targetFieldData.FieldName] = fieldValueToSet; // If we set the BannerImageUrl we also need to update the page to ensure this updated page image "sticks" if (targetFieldData.FieldName == Constants.BannerImageUrlField) { bannerImageUrl = fieldValueToSet.ToString(); } } isDirty = true; LogInfo($"{LogStrings.TransformCopyingMetaDataField} {targetFieldData.FieldName}", LogStrings.Heading_CopyingPageMetadata); } } else { // Log that field in page layout mapping was not found LogWarning(string.Format(LogStrings.Warning_FieldNotFoundInSourcePage, fieldToProcess.Name), LogStrings.Heading_CopyingPageMetadata); } } } } } // Persist changes if (isDirty) { // If we've set a custom thumbnail value then we need to update the page html to mark the isDefaultThumbnail pageslicer property to false if (!string.IsNullOrEmpty(bannerImageUrl)) { this.page.PageListItem[Constants.CanvasContentField] = SetIsDefaultThumbnail(this.page.PageListItem[Constants.CanvasContentField].ToString()); } this.page.PageListItem.UpdateOverwriteVersion(); targetClientContext.Load(this.page.PageListItem); targetClientContext.ExecuteQueryRetry(); isDirty = false; } } } else { LogDebug("Page Layout mapping model not found", LogStrings.Heading_CopyingPageMetadata); } }
public void CanProvisionObjects() { var template = new ProvisioningTemplate(); FileSystemConnector connector = new FileSystemConnector(resourceFolder, ""); template.Connector = connector; template.Files.Add(new Core.Framework.Provisioning.Model.File() { Overwrite = true, Src = fileName, Folder = folder }); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectFiles().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); ctx.Web.EnsureProperties(w => w.ServerRelativeUrl); var serverRelativeUrl = UrlUtility.Combine(ctx.Web.ServerRelativeUrl, UrlUtility.Combine(folder, fileName)); var file = ctx.Web.GetFileByServerRelativeUrl(serverRelativeUrl); // This call will fail as we're creating a file not bound to a list ctx.Load(file); try { ctx.ExecuteQueryRetry(); Assert.IsTrue(file.ServerRelativeUrl.Equals(serverRelativeUrl, StringComparison.InvariantCultureIgnoreCase)); } catch (ServerException ex) { // If this throws ServerException (does not belong to list), then shouldn't be trying to set properties) // Handling the exception stating the "The object specified does not belong to a list." if (ex.ServerErrorCode != -2146232832) { throw; } } } }
private static string GetControlViewVirtualPath(string controlType) { return(UrlUtility.Combine(TemplateVirtualPath, controlType + ".cshtml")); }
public OutgoingQueuePath(OutgoingQueue entity, IBaseDir baseDir) { this.PhysicalPath = Path.Combine(baseDir.Cms_DataPhysicalPath, PathHelper.PublishingFolderName, PATH_NAME); this.VirtualPath = UrlUtility.Combine(baseDir.Cms_DataVirtualPath, PathHelper.PublishingFolderName, PATH_NAME); this.DataFile = Path.Combine(this.PhysicalPath, entity.UUID + ".config"); }
public void CanAddWebPartsToForms() { var template = new ProvisioningTemplate(); FileSystemConnector connector = new FileSystemConnector(resourceFolder + @"\..", ""); template.Connector = connector; var webPart = new WebPart { Column = 1, Row = 1, Contents = webpartcontents, Title = "Script Editor", Order = 0, Zone = "Main" }; var myfile = new Core.Framework.Provisioning.Model.File() { Overwrite = false, Src = "EditForm.aspx", Folder = "SitePages/Forms" }; myfile.WebParts.Add(webPart); template.Files.Add(myfile); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectFiles().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); ctx.Web.EnsureProperties(w => w.ServerRelativeUrl); var file = ctx.Web.GetFileByServerRelativeUrl( UrlUtility.Combine(ctx.Web.ServerRelativeUrl, UrlUtility.Combine("SitePages/Forms", "EditForm.aspx"))); ctx.Load(file, f => f.Exists); ctx.ExecuteQueryRetry(); // first of all do we even find the form ? Assert.IsTrue(file.Exists); var webParts = file.GetLimitedWebPartManager(PersonalizationScope.Shared).WebParts; ctx.Load(webParts, wp => wp.IncludeWithDefaultProperties(w => w.Id, w => w.WebPart, w => w.WebPart.Title)); ctx.ExecuteQueryRetry(); var webPartsArray = webParts.ToArray(); var webPartExists = false; foreach (var webPartDefinition in webPartsArray) { if (webPartDefinition.WebPart.Title == "Script Editor") { webPartExists = true; // cleanup after ourselves if we can find the webpart... webPartDefinition.DeleteWebPart(); } } ctx.ExecuteQueryRetry(); Assert.IsTrue(webPartExists); } }
public WorkflowHistoryPath(TextContent content) { ContentPath = new TextContentPath(content); PhysicalPath = Path.Combine(ContentPath.PhysicalPath, PATH_NAME); VirtualPath = UrlUtility.Combine(ContentPath.VirtualPath, PATH_NAME); }
public WorkflowPath(Workflow workflow) : this(workflow.Repository) { this.PhysicalPath = SettingFile = Path.Combine(PhysicalPath, GetFileName(workflow)); this.VirtualPath = UrlUtility.Combine(this.VirtualPath, GetFileName(workflow)); }
public override TokenParser ProvisionObjects(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, TokenParser tokenParser, ApplyConfiguration configuration) { using (var scope = new PnPMonitoredScope(CoreResources.Provisioning_ObjectHandlers_Provisioning)) { bool nowait = false; if (configuration != null) { nowait = configuration.Tenant.DoNotWaitForSitesToBeFullyCreated; } var sequence = hierarchy.Sequences.FirstOrDefault(s => s.ID == sequenceId); if (sequence != null) { var siteUrls = new Dictionary <Guid, string>(); TokenParser siteTokenParser = null; var tenantThemes = tenant.GetAllTenantThemes(); tenant.Context.Load(tenantThemes); tenant.Context.ExecuteQueryRetry(); foreach (var sitecollection in sequence.SiteCollections) { ClientContext siteContext = null; switch (sitecollection) { case TeamSiteCollection t: { TeamSiteCollectionCreationInformation siteInfo = new TeamSiteCollectionCreationInformation() { Alias = tokenParser.ParseString(t.Alias), DisplayName = tokenParser.ParseString(t.Title), Description = tokenParser.ParseString(t.Description), Classification = tokenParser.ParseString(t.Classification), IsPublic = t.IsPublic, Lcid = (uint)t.Language }; if (Guid.TryParse(t.SiteDesign, out Guid siteDesignId)) { siteInfo.SiteDesignId = siteDesignId; } var groupSiteInfo = Sites.SiteCollection.GetGroupInfoAsync(tenant.Context as ClientContext, siteInfo.Alias).GetAwaiter().GetResult(); if (groupSiteInfo == null) { string graphAccessToken = null; try { graphAccessToken = PnPProvisioningContext.Current.AcquireCookie(Core.Utilities.Graph.GraphHelper.MicrosoftGraphBaseURI); } catch { graphAccessToken = PnPProvisioningContext.Current.AcquireToken(Core.Utilities.Graph.GraphHelper.MicrosoftGraphBaseURI, null); } WriteMessage($"Creating Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress); siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo, configuration.Tenant.DelayAfterModernSiteCreation, noWait: nowait, graphAccessToken: graphAccessToken); } else { if (groupSiteInfo.ContainsKey("siteUrl")) { WriteMessage($"Using existing Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress); siteContext = (tenant.Context as ClientContext).Clone(groupSiteInfo["siteUrl"], configuration.AccessTokens); } } if (t.IsHubSite) { siteContext.Load(siteContext.Site, s => s.Id); siteContext.ExecuteQueryRetry(); RegisterAsHubSite(tenant, siteContext.Url, siteContext.Site.Id, t.HubSiteLogoUrl, t.HubSiteTitle, tokenParser); } if (!string.IsNullOrEmpty(t.Theme)) { var parsedTheme = tokenParser.ParseString(t.Theme); if (tenantThemes.FirstOrDefault(th => th.Name == parsedTheme) != null) { tenant.SetWebTheme(parsedTheme, siteContext.Url); tenant.Context.ExecuteQueryRetry(); } else { WriteMessage($"Theme {parsedTheme} doesn't exist in the tenant, will not be applied", ProvisioningMessageType.Warning); } } if (t.Teamify) { try { WriteMessage($"Teamifying the O365 group connected site at URL - {siteContext.Url}", ProvisioningMessageType.Progress); siteContext.TeamifyAsync().GetAwaiter().GetResult(); } catch (Exception ex) { WriteMessage($"Teamifying site at URL - {siteContext.Url} failed due to an exception:- {ex.Message}", ProvisioningMessageType.Warning); } } if (t.HideTeamify) { try { WriteMessage($"Teamify prompt is now hidden for site at URL - {siteContext.Url}", ProvisioningMessageType.Progress); siteContext.HideTeamifyPrompt().GetAwaiter().GetResult(); } catch (Exception ex) { WriteMessage($"Teamify prompt couldn't be hidden for site at URL - {siteContext.Url} due to an exception:- {ex.Message}", ProvisioningMessageType.Warning); } } siteUrls.Add(t.Id, siteContext.Url); if (!string.IsNullOrEmpty(t.ProvisioningId)) { _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, t.ProvisioningId, siteContext.Url)); siteContext.Web.EnsureProperty(w => w.Id); _additionalTokens.Add(new SequenceSiteIdToken(null, t.ProvisioningId, siteContext.Web.Id)); siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId); _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, t.ProvisioningId, siteContext.Site.Id)); _additionalTokens.Add(new SequenceSiteGroupIdToken(null, t.ProvisioningId, siteContext.Site.GroupId)); } break; } case CommunicationSiteCollection c: { var siteUrl = tokenParser.ParseString(c.Url); if (!siteUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) { var rootSiteUrl = tenant.GetRootSiteUrl(); tenant.Context.ExecuteQueryRetry(); siteUrl = UrlUtility.Combine(rootSiteUrl.Value, siteUrl); } CommunicationSiteCollectionCreationInformation siteInfo = new CommunicationSiteCollectionCreationInformation() { ShareByEmailEnabled = c.AllowFileSharingForGuestUsers, Classification = tokenParser.ParseString(c.Classification), Description = tokenParser.ParseString(c.Description), Lcid = (uint)c.Language, Owner = tokenParser.ParseString(c.Owner), Title = tokenParser.ParseString(c.Title), Url = siteUrl }; if (Guid.TryParse(c.SiteDesign, out Guid siteDesignId)) { siteInfo.SiteDesignId = siteDesignId; } else { if (!string.IsNullOrEmpty(c.SiteDesign)) { siteInfo.SiteDesign = (CommunicationSiteDesign)Enum.Parse(typeof(CommunicationSiteDesign), c.SiteDesign); } else { siteInfo.SiteDesign = CommunicationSiteDesign.Showcase; } } // check if site exists if (tenant.SiteExistsAnywhere(siteInfo.Url) == SiteExistence.Yes) { WriteMessage($"Using existing Communications Site at {siteInfo.Url}", ProvisioningMessageType.Progress); siteContext = (tenant.Context as ClientContext).Clone(siteInfo.Url, configuration.AccessTokens); } else if (tenant.SiteExistsAnywhere(siteInfo.Url) == SiteExistence.Recycled) { var errorMessage = $"The requested Communications Site at {siteInfo.Url} is in the Recycle Bin and cannot be created"; WriteMessage(errorMessage, ProvisioningMessageType.Error); throw new RecycledSiteException(errorMessage); } else { WriteMessage($"Creating Communications Site at {siteInfo.Url}", ProvisioningMessageType.Progress); siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo, configuration.Tenant.DelayAfterModernSiteCreation, noWait: nowait); } if (c.IsHubSite) { siteContext.Load(siteContext.Site, s => s.Id); siteContext.ExecuteQueryRetry(); RegisterAsHubSite(tenant, siteInfo.Url, siteContext.Site.Id, c.HubSiteLogoUrl, c.HubSiteTitle, tokenParser); } if (!string.IsNullOrEmpty(c.Theme)) { var parsedTheme = tokenParser.ParseString(c.Theme); if (tenantThemes.FirstOrDefault(th => th.Name == parsedTheme) != null) { tenant.SetWebTheme(parsedTheme, siteInfo.Url); tenant.Context.ExecuteQueryRetry(); } else { WriteMessage($"Theme {parsedTheme} doesn't exist in the tenant, will not be applied", ProvisioningMessageType.Warning); } } siteUrls.Add(c.Id, siteInfo.Url); if (!string.IsNullOrEmpty(c.ProvisioningId)) { _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, c.ProvisioningId, siteInfo.Url)); siteContext.Web.EnsureProperty(w => w.Id); _additionalTokens.Add(new SequenceSiteIdToken(null, c.ProvisioningId, siteContext.Web.Id)); siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId); _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, c.ProvisioningId, siteContext.Site.Id)); _additionalTokens.Add(new SequenceSiteGroupIdToken(null, c.ProvisioningId, siteContext.Site.GroupId)); } break; } case TeamNoGroupSiteCollection t: { var siteUrl = tokenParser.ParseString(t.Url); TeamNoGroupSiteCollectionCreationInformation siteInfo = new TeamNoGroupSiteCollectionCreationInformation() { Lcid = (uint)t.Language, Url = siteUrl, Title = tokenParser.ParseString(t.Title), Description = tokenParser.ParseString(t.Description), Owner = tokenParser.ParseString(t.Owner) }; if (tenant.SiteExistsAnywhere(siteUrl) == SiteExistence.Yes) { WriteMessage($"Using existing Team Site at {siteUrl}", ProvisioningMessageType.Progress); siteContext = (tenant.Context as ClientContext).Clone(siteUrl, configuration.AccessTokens); } else if (tenant.SiteExistsAnywhere(siteUrl) == SiteExistence.Recycled) { var errorMessage = $"The requested Team Site at {siteUrl} is in the Recycle Bin and cannot be created"; WriteMessage(errorMessage, ProvisioningMessageType.Error); throw new RecycledSiteException(errorMessage); } else { WriteMessage($"Creating Team Site with no Office 365 group at {siteUrl}", ProvisioningMessageType.Progress); siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo, configuration.Tenant.DelayAfterModernSiteCreation, noWait: nowait); } if (t.Groupify) { if (string.IsNullOrEmpty(t.Alias)) { // We generate the alias, if it is missing t.Alias = t.Title.Replace(" ", string.Empty).ToLower(); } // In case we need to groupify the just created site var groupifyInformation = new TeamSiteCollectionGroupifyInformation { Alias = t.Alias, // Mandatory Classification = t.Classification, // Optional Description = t.Description, DisplayName = t.Title, HubSiteId = Guid.Empty, // Optional, so far we skip it IsPublic = t.IsPublic, // Mandatory KeepOldHomePage = t.KeepOldHomePage, // Optional, but we provide it Lcid = (uint)t.Language, Owners = new string[] { t.Owner }, }; tenant.GroupifySite(siteUrl, groupifyInformation); } if (t.IsHubSite) { siteContext.Load(siteContext.Site, s => s.Id); siteContext.ExecuteQueryRetry(); RegisterAsHubSite(tenant, siteContext.Url, siteContext.Site.Id, t.HubSiteLogoUrl, t.HubSiteTitle, tokenParser); } if (!string.IsNullOrEmpty(t.Theme)) { var parsedTheme = tokenParser.ParseString(t.Theme); if (tenantThemes.FirstOrDefault(th => th.Name == parsedTheme) != null) { tenant.SetWebTheme(parsedTheme, siteContext.Url); tenant.Context.ExecuteQueryRetry(); } else { WriteMessage($"Theme {parsedTheme} doesn't exist in the tenant, will not be applied", ProvisioningMessageType.Warning); } } siteUrls.Add(t.Id, siteContext.Url); if (!string.IsNullOrEmpty(t.ProvisioningId)) { _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, t.ProvisioningId, siteContext.Url)); siteContext.Web.EnsureProperty(w => w.Id); _additionalTokens.Add(new SequenceSiteIdToken(null, t.ProvisioningId, siteContext.Web.Id)); siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId); _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, t.ProvisioningId, siteContext.Site.Id)); _additionalTokens.Add(new SequenceSiteGroupIdToken(null, t.ProvisioningId, siteContext.Site.GroupId)); } break; } } var web = siteContext.Web; if (siteTokenParser == null) { siteTokenParser = new TokenParser(tenant, hierarchy, configuration.ToApplyingInformation()); foreach (var token in _additionalTokens) { siteTokenParser.AddToken(token); // Add the token to the global token parser, too tokenParser.AddToken(token); } } foreach (var subsite in sitecollection.Sites) { var subSiteObject = (TeamNoGroupSubSite)subsite; web.EnsureProperties(w => w.Webs.IncludeWithDefaultProperties(), w => w.ServerRelativeUrl); siteTokenParser = CreateSubSites(hierarchy, siteTokenParser, sitecollection, siteContext, web, subSiteObject); } siteTokenParser = null; } // System.Threading.Thread.Sleep(TimeSpan.FromMinutes(10)); WriteMessage("Applying templates", ProvisioningMessageType.Progress); var currentSite = ""; var provisioningTemplateApplyingInformation = configuration.ToApplyingInformation(); provisioningTemplateApplyingInformation.ProgressDelegate = (string message, int step, int total) => { configuration.ProgressDelegate?.Invoke($"{currentSite} : {message}", step, total); }; foreach (var sitecollection in sequence.SiteCollections) { currentSite = sitecollection.ProvisioningId != null ? sitecollection.ProvisioningId : sitecollection.Title; siteUrls.TryGetValue(sitecollection.Id, out string siteUrl); if (siteUrl != null) { using (var clonedContext = tenant.Context.Clone(siteUrl, configuration.AccessTokens)) { var web = clonedContext.Web; foreach (var templateRef in sitecollection.Templates) { var provisioningTemplate = hierarchy.Templates.FirstOrDefault(t => t.Id == templateRef); if (provisioningTemplate != null) { provisioningTemplate.Connector = hierarchy.Connector; //if (siteTokenParser == null) //{ siteTokenParser = new TokenParser(web, provisioningTemplate, configuration.ToApplyingInformation()); foreach (var token in _additionalTokens) { siteTokenParser.AddToken(token); } //} //else //{ // siteTokenParser.Rebase(web, provisioningTemplate); //} WriteMessage($"Applying Template", ProvisioningMessageType.Progress); new SiteToTemplateConversion().ApplyRemoteTemplate(web, provisioningTemplate, provisioningTemplateApplyingInformation, true, siteTokenParser); } else { WriteMessage($"Referenced template ID {templateRef} not found", ProvisioningMessageType.Error); } } if (siteTokenParser == null) { siteTokenParser = new TokenParser(tenant, hierarchy, configuration.ToApplyingInformation()); foreach (var token in _additionalTokens) { siteTokenParser.AddToken(token); } } foreach (var subsite in sitecollection.Sites) { var subSiteObject = (TeamNoGroupSubSite)subsite; web.EnsureProperties(w => w.Webs.IncludeWithDefaultProperties(), w => w.ServerRelativeUrl); siteTokenParser = ApplySubSiteTemplates(hierarchy, siteTokenParser, sitecollection, clonedContext, web, subSiteObject, provisioningTemplateApplyingInformation); } if (sitecollection.IsHubSite) { RESTUtilities.ExecuteGet(web, "/_api/web/hubsitedata(true)").GetAwaiter().GetResult(); } } } } } return(tokenParser); } }
private ProvisioningTemplate GetFileContents(Web web, ProvisioningTemplate template, string welcomePageUrl, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope) { var homepageUrl = web.RootFolder.WelcomePage; if (string.IsNullOrEmpty(homepageUrl)) { homepageUrl = "Default.aspx"; } var fullUri = new Uri(UrlUtility.Combine(web.Url, homepageUrl)); var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/'); var fileName = fullUri.Segments[fullUri.Segments.Count() - 1]; var webParts = web.GetWebParts(welcomePageUrl); var file = web.GetFileByServerRelativeUrl(welcomePageUrl); file.EnsureProperty(f => f.Level); var containerPath = folderPath.StartsWith(web.ServerRelativeUrl) && web.ServerRelativeUrl != "/" ? folderPath.Substring(web.ServerRelativeUrl.Length) : folderPath; var container = containerPath.Trim('/').Replace("%20", " ").Replace("/", "\\"); var homeFile = new Model.File() { Folder = Tokenize(folderPath, web.Url), Src = !string.IsNullOrEmpty(container) ? $"{container}\\{fileName}" : fileName, Overwrite = true, Level = (Model.FileLevel)Enum.Parse(typeof(Model.FileLevel), file.Level.ToString()) }; // Add field values to file RetrieveFieldValues(web, file, homeFile); // Add WebParts to file foreach (var webPart in webParts) { var webPartxml = TokenizeWebPartXml(web, web.GetWebPartXml(webPart.Id, welcomePageUrl)); Model.WebPart newWp = new Model.WebPart() { Title = webPart.WebPart.Title, Row = (uint)webPart.WebPart.ZoneIndex, Order = (uint)webPart.WebPart.ZoneIndex, Contents = webPartxml }; #if !SP2016 // As long as we've no CSOM library that has the ZoneID we can't use the version check as things don't compile... if (web.Context.HasMinimalServerLibraryVersion(Constants.MINIMUMZONEIDREQUIREDSERVERVERSION)) { newWp.Zone = webPart.ZoneId; } #endif homeFile.WebParts.Add(newWp); } template.Files.Add(homeFile); // Persist file using connector if (creationInfo.PersistBrandingFiles) { PersistFile(web, creationInfo, scope, folderPath, fileName); } return(template); }
protected override void ExecuteCmdlet() { if (Url.StartsWith("/")) { // prefix the url with the current web url Url = UrlUtility.Combine(ClientContext.Url, Url); } var accessToken = this.ClientContext.GetAccessToken(); var method = new HttpMethod(Method.ToString()); using (var handler = new HttpClientHandler()) { // we're not in app-only or user + app context, so let's fall back to cookie based auth if (string.IsNullOrEmpty(accessToken)) { SetAuthenticationCookies(handler, ClientContext); } using (var httpClient = new PnPHttpProvider(handler)) { var requestUrl = Url; HttpRequestMessage request = new HttpRequestMessage(method, requestUrl); request.Headers.Add("accept", "application/json;odata=nometadata"); if (Method == HttpRequestMethod.Merge) { method = HttpMethod.Post; request.Headers.Add("X-HTTP-Method", "MERGE"); } if (Method == HttpRequestMethod.Merge || Method == HttpRequestMethod.Delete) { request.Headers.Add("IF-MATCH", "*"); } if (!string.IsNullOrEmpty(accessToken)) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); } else { if (ClientContext.Credentials is NetworkCredential networkCredential) { handler.Credentials = networkCredential; } } request.Headers.Add("X-RequestDigest", ClientContext.GetRequestDigestAsync().GetAwaiter().GetResult()); if (Method == HttpRequestMethod.Post) { if (string.IsNullOrEmpty(ContentType)) { ContentType = "application/json"; } var contentString = Content is string?Content.ToString() : JsonSerializer.Serialize(Content); request.Content = new StringContent(contentString, System.Text.Encoding.UTF8); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType); } HttpResponseMessage response = httpClient.SendAsync(request, new System.Threading.CancellationToken()).Result; if (response.IsSuccessStatusCode) { var responseString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (responseString != null) { WriteObject(JsonSerializer.Deserialize <Hashtable>(responseString)); } } else { // Something went wrong... throw new Exception(response.Content.ReadAsStringAsync().GetAwaiter().GetResult()); } } } }
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { web.EnsureProperties(w => w.ServerRelativeUrl); // determine pages library string pagesLibrary = "SitePages"; var pagesLibraryList = web.GetListByUrl(pagesLibrary, p => p.RootFolder); List <string> preCreatedPages = new List <string>(); var currentPageIndex = 0; // pre create the needed pages so we can fill the needed tokens which might be used later on when we put web parts on those pages foreach (var clientSidePage in template.ClientSidePages) { string pageName = $"{System.IO.Path.GetFileNameWithoutExtension(parser.ParseString(clientSidePage.PageName))}.aspx"; string url = $"{pagesLibrary}/{pageName}"; if (clientSidePage.Layout == "Article" && clientSidePage.PromoteAsTemplate) { url = $"{pagesLibrary}/{Pages.ClientSidePage.GetTemplatesFolder(pagesLibraryList)}/{pageName}"; } // Write page level status messages, needed in case many pages are provisioned currentPageIndex++; WriteMessage($"ClientSidePage|Create {pageName}|{currentPageIndex}|{template.ClientSidePages.Count}", ProvisioningMessageType.Progress); url = UrlUtility.Combine(web.ServerRelativeUrl, url); var exists = true; try { var file = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(url)); web.Context.Load(file, f => f.UniqueId, f => f.ServerRelativePath, f => f.Exists); web.Context.ExecuteQueryRetry(); // Fill token parser.AddToken(new PageUniqueIdToken(web, file.ServerRelativePath.DecodedUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), file.UniqueId)); parser.AddToken(new PageUniqueIdEncodedToken(web, file.ServerRelativePath.DecodedUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), file.UniqueId)); exists = file.Exists; } catch (ServerException ex) { if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException") { exists = false; } } if (!exists) { // Pre-create the page Pages.ClientSidePage page = web.AddClientSidePage(pageName); // Set page layout now, because once it's set, it can't be changed. if (!string.IsNullOrEmpty(clientSidePage.Layout)) { page.LayoutType = (Pages.ClientSidePageLayoutType)Enum.Parse(typeof(Pages.ClientSidePageLayoutType), clientSidePage.Layout); } if (clientSidePage.Layout == "Article" && clientSidePage.PromoteAsTemplate) { page.SaveAsTemplate(pageName); } else { page.Save(pageName); } var file = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(url)); web.Context.Load(file, f => f.UniqueId, f => f.ServerRelativePath); web.Context.ExecuteQueryRetry(); // Fill token parser.AddToken(new PageUniqueIdToken(web, file.ServerRelativePath.DecodedUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), file.UniqueId)); parser.AddToken(new PageUniqueIdEncodedToken(web, file.ServerRelativePath.DecodedUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), file.UniqueId)); // Track that we pre-added this page preCreatedPages.Add(url); } } currentPageIndex = 0; // Iterate over the pages and create/update them foreach (var clientSidePage in template.ClientSidePages) { string pageName = $"{System.IO.Path.GetFileNameWithoutExtension(parser.ParseString(clientSidePage.PageName))}.aspx"; string url = $"{pagesLibrary}/{pageName}"; if (clientSidePage.Layout == "Article" && clientSidePage.PromoteAsTemplate) { url = $"{pagesLibrary}/{Pages.ClientSidePage.GetTemplatesFolder(pagesLibraryList)}/{pageName}"; } // Write page level status messages, needed in case many pages are provisioned currentPageIndex++; WriteMessage($"ClientSidePage|{pageName}|{currentPageIndex}|{template.ClientSidePages.Count}", ProvisioningMessageType.Progress); url = UrlUtility.Combine(web.ServerRelativeUrl, url); var exists = true; try { var file = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(url)); web.Context.Load(file); web.Context.ExecuteQueryRetry(); } catch (ServerException ex) { if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException") { exists = false; } } Pages.ClientSidePage page = null; if (exists) { if (clientSidePage.Overwrite || preCreatedPages.Contains(url)) { if (clientSidePage.Layout == "Article" && clientSidePage.PromoteAsTemplate) { // Get the existing template page page = web.LoadClientSidePage($"{Pages.ClientSidePage.GetTemplatesFolder(pagesLibraryList)}/{pageName}"); } else { // Get the existing page page = web.LoadClientSidePage(pageName); } // Clear the page page.ClearPage(); } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ClientSidePages_NoOverWrite, pageName); continue; } } else { // Create new client side page page = web.AddClientSidePage(pageName); } // Set page title string newTitle = parser.ParseString(clientSidePage.Title); if (page.PageTitle != newTitle) { page.PageTitle = newTitle; } // Page Header if (clientSidePage.Header != null) { switch (clientSidePage.Header.Type) { case ClientSidePageHeaderType.None: { page.RemovePageHeader(); break; } case ClientSidePageHeaderType.Default: { page.SetDefaultPageHeader(); break; } case ClientSidePageHeaderType.Custom: { var serverRelativeImageUrl = parser.ParseString(clientSidePage.Header.ServerRelativeImageUrl); if (clientSidePage.Header.TranslateX.HasValue && clientSidePage.Header.TranslateY.HasValue) { page.SetCustomPageHeader(serverRelativeImageUrl, clientSidePage.Header.TranslateX.Value, clientSidePage.Header.TranslateY.Value); } else { page.SetCustomPageHeader(serverRelativeImageUrl); } page.PageHeader.TextAlignment = (Pages.ClientSidePageHeaderTitleAlignment)Enum.Parse(typeof(ClientSidePageHeaderTextAlignment), clientSidePage.Header.TextAlignment.ToString()); page.PageHeader.LayoutType = (Pages.ClientSidePageHeaderLayoutType)Enum.Parse(typeof(ClientSidePageHeaderLayoutType), clientSidePage.Header.LayoutType.ToString()); page.PageHeader.ShowTopicHeader = clientSidePage.Header.ShowTopicHeader; page.PageHeader.ShowPublishDate = clientSidePage.Header.ShowPublishDate; page.PageHeader.TopicHeader = clientSidePage.Header.TopicHeader; page.PageHeader.AlternativeText = clientSidePage.Header.AlternativeText; page.PageHeader.Authors = clientSidePage.Header.Authors; page.PageHeader.AuthorByLine = clientSidePage.Header.AuthorByLine; page.PageHeader.AuthorByLineId = clientSidePage.Header.AuthorByLineId; break; } } } // Set page layout if (!string.IsNullOrEmpty(clientSidePage.Layout)) { page.LayoutType = (Pages.ClientSidePageLayoutType)Enum.Parse(typeof(Pages.ClientSidePageLayoutType), clientSidePage.Layout); } // Add content on the page, not needed for repost pages if (page.LayoutType != Pages.ClientSidePageLayoutType.RepostPage) { // Load existing available controls var componentsToAdd = page.AvailableClientSideComponents().ToList(); // if no section specified then add a default single column section if (!clientSidePage.Sections.Any()) { clientSidePage.Sections.Add(new CanvasSection() { Type = CanvasSectionType.OneColumn, Order = 10 }); } int sectionCount = -1; // Apply the "layout" and content foreach (var section in clientSidePage.Sections) { sectionCount++; switch (section.Type) { case CanvasSectionType.OneColumn: page.AddSection(Pages.CanvasSectionTemplate.OneColumn, section.Order, (Int32)section.BackgroundEmphasis); break; case CanvasSectionType.OneColumnFullWidth: page.AddSection(Pages.CanvasSectionTemplate.OneColumnFullWidth, section.Order, (Int32)section.BackgroundEmphasis); break; case CanvasSectionType.TwoColumn: page.AddSection(Pages.CanvasSectionTemplate.TwoColumn, section.Order, (Int32)section.BackgroundEmphasis); break; case CanvasSectionType.ThreeColumn: page.AddSection(Pages.CanvasSectionTemplate.ThreeColumn, section.Order, (Int32)section.BackgroundEmphasis); break; case CanvasSectionType.TwoColumnLeft: page.AddSection(Pages.CanvasSectionTemplate.TwoColumnLeft, section.Order, (Int32)section.BackgroundEmphasis); break; case CanvasSectionType.TwoColumnRight: page.AddSection(Pages.CanvasSectionTemplate.TwoColumnRight, section.Order, (Int32)section.BackgroundEmphasis); break; default: page.AddSection(Pages.CanvasSectionTemplate.OneColumn, section.Order, (Int32)section.BackgroundEmphasis); break; } // Add controls to the section if (section.Controls.Any()) { // Safety measure: reset column order to 1 for columns marked with 0 or lower foreach (var control in section.Controls.Where(p => p.Column <= 0).ToList()) { control.Column = 1; } foreach (CanvasControl control in section.Controls) { Pages.ClientSideComponent baseControl = null; // Is it a text control? if (control.Type == WebPartType.Text) { Pages.ClientSideText textControl = new Pages.ClientSideText(); if (control.ControlProperties.Any()) { var textProperty = control.ControlProperties.First(); textControl.Text = parser.ParseString(textProperty.Value); } else { if (!string.IsNullOrEmpty(control.JsonControlData)) { var json = JsonConvert.DeserializeObject <Dictionary <string, string> >(control.JsonControlData); if (json.Count > 0) { textControl.Text = parser.ParseString(json.First().Value); } } } // Reduce column number by 1 due 0 start indexing page.AddControl(textControl, page.Sections[sectionCount].Columns[control.Column - 1], control.Order); } // It is a web part else { // apply token parsing on the web part properties control.JsonControlData = parser.ParseString(control.JsonControlData); // perform processing of web part properties (e.g. include listid property based list title property) var webPartPostProcessor = CanvasControlPostProcessorFactory.Resolve(control); webPartPostProcessor.Process(control, page); // Is a custom developed client side web part (3rd party) if (control.Type == WebPartType.Custom) { if (!string.IsNullOrEmpty(control.CustomWebPartName)) { baseControl = componentsToAdd.FirstOrDefault(p => p.Name.Equals(control.CustomWebPartName, StringComparison.InvariantCultureIgnoreCase)); } else if (control.ControlId != Guid.Empty) { baseControl = componentsToAdd.FirstOrDefault(p => p.Id.Equals($"{{{control.ControlId.ToString()}}}", StringComparison.CurrentCultureIgnoreCase)); if (baseControl == null) { baseControl = componentsToAdd.FirstOrDefault(p => p.Id.Equals(control.ControlId.ToString(), StringComparison.InvariantCultureIgnoreCase)); } } } // Is an OOB client side web part (1st party) else { string webPartName = ""; switch (control.Type) { case WebPartType.Image: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Image); break; case WebPartType.BingMap: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.BingMap); break; case WebPartType.ContentEmbed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ContentEmbed); break; case WebPartType.ContentRollup: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ContentRollup); break; case WebPartType.DocumentEmbed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.DocumentEmbed); break; case WebPartType.Events: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Events); break; case WebPartType.GroupCalendar: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.GroupCalendar); break; case WebPartType.Hero: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Hero); break; case WebPartType.ImageGallery: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ImageGallery); break; case WebPartType.LinkPreview: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.LinkPreview); break; case WebPartType.List: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.List); break; case WebPartType.NewsFeed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.NewsFeed); break; case WebPartType.NewsReel: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.NewsReel); break; case WebPartType.PageTitle: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.PageTitle); break; case WebPartType.People: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.People); break; case WebPartType.PowerBIReportEmbed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.PowerBIReportEmbed); break; case WebPartType.QuickChart: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.QuickChart); break; case WebPartType.QuickLinks: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.QuickLinks); break; case WebPartType.SiteActivity: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.SiteActivity); break; case WebPartType.VideoEmbed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.VideoEmbed); break; case WebPartType.YammerEmbed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.YammerEmbed); break; case WebPartType.CustomMessageRegion: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.CustomMessageRegion); break; case WebPartType.Divider: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Divider); break; case WebPartType.MicrosoftForms: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.MicrosoftForms); break; case WebPartType.Spacer: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Spacer); break; case WebPartType.ClientWebPart: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ClientWebPart); break; } baseControl = componentsToAdd.FirstOrDefault(p => p.Name.Equals(webPartName, StringComparison.InvariantCultureIgnoreCase)); } if (baseControl != null) { Pages.ClientSideWebPart myWebPart = new Pages.ClientSideWebPart(baseControl) { Order = control.Order }; if (!String.IsNullOrEmpty(control.JsonControlData)) { var json = JsonConvert.DeserializeObject <JObject>(control.JsonControlData); if (json["instanceId"] != null && json["instanceId"].Type != JTokenType.Null) { if (Guid.TryParse(json["instanceId"].Value <string>(), out Guid instanceId)) { myWebPart.instanceId = instanceId; } } } // Reduce column number by 1 due 0 start indexing page.AddControl(myWebPart, page.Sections[sectionCount].Columns[control.Column - 1], control.Order); // set properties using json string if (!String.IsNullOrEmpty(control.JsonControlData)) { myWebPart.PropertiesJson = control.JsonControlData; } // set using property collection if (control.ControlProperties.Any()) { // grab the "default" properties so we can deduct their types, needed to correctly apply the set properties var controlManifest = JObject.Parse(baseControl.Manifest); JToken controlProperties = null; if (controlManifest != null) { controlProperties = controlManifest.SelectToken("preconfiguredEntries[0].properties"); } foreach (var property in control.ControlProperties) { Type propertyType = typeof(string); if (controlProperties != null) { var defaultProperty = controlProperties.SelectToken(property.Key, false); if (defaultProperty != null) { propertyType = Type.GetType($"System.{defaultProperty.Type.ToString()}"); if (propertyType == null) { if (defaultProperty.Type.ToString().Equals("integer", StringComparison.InvariantCultureIgnoreCase)) { propertyType = typeof(int); } } } } myWebPart.Properties[property.Key] = JToken.FromObject(Convert.ChangeType(parser.ParseString(property.Value), propertyType)); } } } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ClientSidePages_BaseControlNotFound, control.ControlId, control.CustomWebPartName); } } } } } } // Persist the page if (clientSidePage.Layout == "Article" && clientSidePage.PromoteAsTemplate) { page.SaveAsTemplate(pageName); } else { page.Save(pageName); } // Update page content type bool isDirty = false; if (!string.IsNullOrEmpty(clientSidePage.ContentTypeID)) { page.PageListItem[ContentTypeIdField] = clientSidePage.ContentTypeID; page.PageListItem.Update(); web.Context.Load(page.PageListItem); isDirty = true; } if (clientSidePage.PromoteAsTemplate && page.LayoutType == Pages.ClientSidePageLayoutType.Article) { // Choice field, currently there's only one value possible and that's Template page.PageListItem[SPSitePageFlagsField] = ";#Template;#"; page.PageListItem.Update(); web.Context.Load(page.PageListItem); isDirty = true; } if (isDirty) { web.Context.ExecuteQueryRetry(); } if (clientSidePage.FieldValues != null && clientSidePage.FieldValues.Any()) { ListItemUtilities.UpdateListItem(page.PageListItem, parser, clientSidePage.FieldValues, ListItemUtilities.ListItemUpdateType.UpdateOverwriteVersion); } // Set page property bag values if (clientSidePage.Properties != null && clientSidePage.Properties.Any()) { string pageFilePath = page.PageListItem[FileRefField].ToString(); var pageFile = web.GetFileByServerRelativeUrl(pageFilePath); web.Context.Load(pageFile, p => p.Properties); foreach (var pageProperty in clientSidePage.Properties) { if (!string.IsNullOrEmpty(pageProperty.Key)) { pageFile.Properties[pageProperty.Key] = pageProperty.Value; } } pageFile.Update(); web.Context.Load(page.PageListItem); web.Context.ExecuteQueryRetry(); } if (page.LayoutType != Pages.ClientSidePageLayoutType.SingleWebPartAppPage) { // Set commenting, ignore on pages of the type Home or page templates if (page.LayoutType != Pages.ClientSidePageLayoutType.Home && !clientSidePage.PromoteAsTemplate) { // Make it a news page if requested if (clientSidePage.PromoteAsNewsArticle) { page.PromoteAsNewsArticle(); } } if (page.LayoutType != Pages.ClientSidePageLayoutType.RepostPage) { if (clientSidePage.EnableComments) { page.EnableComments(); } else { page.DisableComments(); } } } // Publish page, page templates cannot be published if (clientSidePage.Publish && !clientSidePage.PromoteAsTemplate) { page.Publish(); } // Set any security on the page if (clientSidePage.Security != null && clientSidePage.Security.RoleAssignments.Count != 0) { web.Context.Load(page.PageListItem); web.Context.ExecuteQueryRetry(); page.PageListItem.SetSecurity(parser, clientSidePage.Security); } } } WriteMessage("Done processing Client Side Pages", ProvisioningMessageType.Completed); return(parser); }
private IEnumerable <object> GetContents(string FolderSiteRelativeUrl) { Folder targetFolder = null; if (ParameterSetName == ParameterSet_FOLDERSBYPIPE && Identity != null) { targetFolder = Identity.GetFolder(CurrentWeb); } else { string serverRelativeUrl = null; if (!string.IsNullOrEmpty(FolderSiteRelativeUrl)) { var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); serverRelativeUrl = UrlUtility.Combine(webUrl, FolderSiteRelativeUrl); } targetFolder = (string.IsNullOrEmpty(FolderSiteRelativeUrl)) ? CurrentWeb.RootFolder : CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl)); } IEnumerable <File> files = null; IEnumerable <Folder> folders = null; if (ItemType == "File" || ItemType == "All") { files = ClientContext.LoadQuery(targetFolder.Files).OrderBy(f => f.Name); if (!string.IsNullOrEmpty(ItemName)) { files = files.Where(f => f.Name.Equals(ItemName, StringComparison.InvariantCultureIgnoreCase)); } } if (ItemType == "Folder" || ItemType == "All" || Recursive) { folders = ClientContext.LoadQuery(targetFolder.Folders).OrderBy(f => f.Name); if (!string.IsNullOrEmpty(ItemName)) { folders = folders.Where(f => f.Name.Equals(ItemName, StringComparison.InvariantCultureIgnoreCase)); } } ClientContext.ExecuteQueryRetry(); IEnumerable <object> folderContent = null; switch (ItemType) { case "All": folderContent = folders.Concat <object>(files); break; case "Folder": folderContent = folders; break; default: folderContent = files; break; } if (Recursive && folders.Count() > 0) { foreach (var folder in folders) { var relativeUrl = folder.ServerRelativeUrl.Replace(CurrentWeb.ServerRelativeUrl, ""); var subFolderContents = GetContents(relativeUrl); folderContent = folderContent.Concat <object>(subFolderContents); } } return(folderContent); }
/// <summary> /// Ensures that we have context of the source site collection /// </summary> /// <param name="context">Source site context</param> internal void EnsureAssetContextIfRequired(ClientContext context, string sourceUrl) { // There is two scenarios to check // - If the asset resides on the root site collection // - If the asset resides on another subsite // - If the asset resides on a subsite below this context try { context.Site.EnsureProperties(o => o.ServerRelativeUrl, o => o.Url, o => o.RootWeb.Id); context.Web.EnsureProperties(o => o.ServerRelativeUrl, o => o.Id); string match = string.Empty; // Break the URL into segments and deteremine which URL detects the file in the structure. // Use Web IDs to validate content isnt the same on the root var fullSiteCollectionUrl = context.Site.Url; var relativeSiteCollUrl = context.Site.ServerRelativeUrl; var sourceCtxUrl = context.Web.GetUrl(); // Lets break into segments var fileName = Path.GetFileName(sourceUrl); // Could already be relative //var sourceUrlWithOutBaseAddr = sourceUrl.Replace(fullSiteCollectionUrl, "").Replace(relativeSiteCollUrl,""); var urlSegments = sourceUrl.Split('/'); // Need null tests var filteredUrlSegments = urlSegments.Where(o => !string.IsNullOrEmpty(o) && o != fileName).Reverse(); //Assume the last segment is the filename //Assume the segment before the last is either a folder or library //Url to strip back until detected as subweb var remainingUrl = sourceUrl.Replace(fileName, ""); //remove file name //Urls to try to determine web foreach (var segment in filteredUrlSegments) //Assume the segment before the last is either a folder or library { try { var testUrl = UrlUtility.Combine(fullSiteCollectionUrl.ToLower(), remainingUrl.ToLower().Replace(relativeSiteCollUrl.ToLower(), "")); //No need to recurse this var exists = context.WebExistsFullUrl(testUrl); if (exists) { //winner match = testUrl; break; } else { remainingUrl = remainingUrl.TrimEnd('/').TrimEnd($"{segment}".ToCharArray()); } } catch { // Nope not the right web - Swallow } } // Check if the asset is on the root site collection if (match == string.Empty) { // Does it contain a relative reference if (sourceUrl.StartsWith("/") && !sourceUrl.ContainsIgnoringCasing(context.Web.GetUrl())) { match = fullSiteCollectionUrl.ToLower(); } } if (match != string.Empty && !match.Equals(context.Web.GetUrl(), StringComparison.InvariantCultureIgnoreCase)) { _sourceClientContext = context.Clone(match); LogDebug("Source Context Switched", "EsureAssetContextIfRequired"); } } catch (Exception ex) { LogError(LogStrings.Error_CannotGetSiteCollContext, LogStrings.Heading_AssetTransfer, ex); } }
protected override void ExecuteCmdlet() { var serverRelativeUrl = string.Empty; var webUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!Url.ToLower().StartsWith(webUrl.ToLower())) { serverRelativeUrl = UrlUtility.Combine(webUrl, Url); } else { serverRelativeUrl = Url; } File file; #if ONPREMISES file = SelectedWeb.GetFileByServerRelativeUrl(serverRelativeUrl); #else file = SelectedWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl)); #endif ClientContext.Load(file, f => f.Exists, f => f.Versions.IncludeWithDefaultProperties(i => i.CreatedBy)); ClientContext.ExecuteQueryRetry(); if (file.Exists) { var versions = file.Versions; switch (ParameterSetName) { case ParameterSetName_ALL: { if (Force || ShouldContinue("Remove all versions?", Resources.Confirm)) { versions.DeleteAll(); ClientContext.ExecuteQueryRetry(); } break; } case ParameterSetName_BYID: { if (Force || ShouldContinue("Remove a version?", Resources.Confirm)) { if (!string.IsNullOrEmpty(Identity.Label)) { versions.DeleteByLabel(Identity.Label); ClientContext.ExecuteQueryRetry(); } else if (Identity.Id != -1) { versions.DeleteByID(Identity.Id); ClientContext.ExecuteQueryRetry(); } } break; } } } else { throw new PSArgumentException("File not found", nameof(Url)); } }
public OutgoingQueuePath(IBaseDir baseDir) { this.PhysicalPath = Path.Combine(baseDir.Cms_DataPhysicalPath, PathHelper.PublishingFolderName, PATH_NAME); this.VirtualPath = UrlUtility.Combine(baseDir.Cms_DataVirtualPath, PathHelper.PublishingFolderName, PATH_NAME); }
protected override void ExecuteCmdlet() { var serverRelativeUrl = string.Empty; if (string.IsNullOrEmpty(Path)) { Path = SessionState.Path.CurrentFileSystemLocation.Path; } else { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } } var webUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!Url.ToLower().StartsWith(webUrl.ToLower())) { serverRelativeUrl = UrlUtility.Combine(webUrl, Url); } else { serverRelativeUrl = Url; } File file; switch (ParameterSetName) { case URLTOPATH: SelectedWeb.SaveFileToLocal(serverRelativeUrl, Path, Filename); break; case URLASFILEOBJECT: file = SelectedWeb.GetFileByServerRelativeUrl(serverRelativeUrl); ClientContext.Load(file, f => f.Author, f => f.Length, f => f.ModifiedBy, f => f.Name, f => f.TimeCreated, f => f.TimeLastModified, f => f.Title); ClientContext.ExecuteQueryRetry(); WriteObject(file); break; case URLASLISTITEM: file = SelectedWeb.GetFileByServerRelativeUrl(serverRelativeUrl); ClientContext.Load(file, f => f.Exists, f => f.ListItemAllFields); ClientContext.ExecuteQueryRetry(); if (file.Exists) { WriteObject(file.ListItemAllFields); } break; case URLASSTRING: WriteObject(SelectedWeb.GetFileAsString(serverRelativeUrl)); break; } }
public override TokenParser ProvisionObjects(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, TokenParser tokenParser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(CoreResources.Provisioning_ObjectHandlers_Provisioning)) { var sequence = hierarchy.Sequences.FirstOrDefault(s => s.ID == sequenceId); if (sequence != null) { var siteUrls = new Dictionary <Guid, string>(); TokenParser siteTokenParser = null; foreach (var sitecollection in sequence.SiteCollections) { ClientContext siteContext = null; switch (sitecollection) { case TeamSiteCollection t: { TeamSiteCollectionCreationInformation siteInfo = new TeamSiteCollectionCreationInformation() { Alias = tokenParser.ParseString(t.Alias), DisplayName = tokenParser.ParseString(t.Title), Description = tokenParser.ParseString(t.Description), Classification = tokenParser.ParseString(t.Classification), IsPublic = t.IsPublic }; var groupSiteInfo = Sites.SiteCollection.GetGroupInfo(tenant.Context as ClientContext, siteInfo.Alias).GetAwaiter().GetResult(); if (groupSiteInfo == null) { WriteMessage($"Creating Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress); siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo); } else { if (groupSiteInfo.ContainsKey("siteUrl")) { WriteMessage($"Using existing Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress); siteContext = (tenant.Context as ClientContext).Clone(groupSiteInfo["siteUrl"], applyingInformation.AccessTokens); } } if (t.IsHubSite) { RegisterAsHubSite(tenant, siteContext.Url, t.HubSiteLogoUrl); } if (!string.IsNullOrEmpty(t.Theme)) { var parsedTheme = tokenParser.ParseString(t.Theme); tenant.SetWebTheme(parsedTheme, siteContext.Url); tenant.Context.ExecuteQueryRetry(); } siteUrls.Add(t.Id, siteContext.Url); if (!string.IsNullOrEmpty(t.ProvisioningId)) { _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, t.ProvisioningId, siteContext.Url)); siteContext.Web.EnsureProperty(w => w.Id); _additionalTokens.Add(new SequenceSiteIdToken(null, t.ProvisioningId, siteContext.Web.Id)); siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId); _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, t.ProvisioningId, siteContext.Site.Id)); _additionalTokens.Add(new SequenceSiteGroupIdToken(null, t.ProvisioningId, siteContext.Site.GroupId)); } break; } case CommunicationSiteCollection c: { var siteUrl = tokenParser.ParseString(c.Url); if (!siteUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) { var rootSiteUrl = tenant.GetRootSiteUrl(); tenant.Context.ExecuteQueryRetry(); siteUrl = UrlUtility.Combine(rootSiteUrl.Value, siteUrl); } CommunicationSiteCollectionCreationInformation siteInfo = new CommunicationSiteCollectionCreationInformation() { ShareByEmailEnabled = c.AllowFileSharingForGuestUsers, Classification = tokenParser.ParseString(c.Classification), Description = tokenParser.ParseString(c.Description), Lcid = (uint)c.Language, Owner = tokenParser.ParseString(c.Owner), Title = tokenParser.ParseString(c.Title), Url = siteUrl }; if (Guid.TryParse(c.SiteDesign, out Guid siteDesignId)) { siteInfo.SiteDesignId = siteDesignId; } else { if (!string.IsNullOrEmpty(c.SiteDesign)) { siteInfo.SiteDesign = (CommunicationSiteDesign)Enum.Parse(typeof(CommunicationSiteDesign), c.SiteDesign); } else { siteInfo.SiteDesign = CommunicationSiteDesign.Showcase; } } // check if site exists if (tenant.SiteExists(siteInfo.Url)) { WriteMessage($"Using existing Communications Site at {siteInfo.Url}", ProvisioningMessageType.Progress); siteContext = (tenant.Context as ClientContext).Clone(siteInfo.Url, applyingInformation.AccessTokens); } else { WriteMessage($"Creating Communications Site at {siteInfo.Url}", ProvisioningMessageType.Progress); siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo); } if (c.IsHubSite) { RegisterAsHubSite(tenant, siteInfo.Url, c.HubSiteLogoUrl); } if (!string.IsNullOrEmpty(c.Theme)) { var parsedTheme = tokenParser.ParseString(c.Theme); tenant.SetWebTheme(parsedTheme, siteInfo.Url); tenant.Context.ExecuteQueryRetry(); } siteUrls.Add(c.Id, siteInfo.Url); if (!string.IsNullOrEmpty(c.ProvisioningId)) { _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, c.ProvisioningId, siteInfo.Url)); siteContext.Web.EnsureProperty(w => w.Id); _additionalTokens.Add(new SequenceSiteIdToken(null, c.ProvisioningId, siteContext.Web.Id)); siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId); _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, c.ProvisioningId, siteContext.Site.Id)); _additionalTokens.Add(new SequenceSiteGroupIdToken(null, c.ProvisioningId, siteContext.Site.GroupId)); } break; } case TeamNoGroupSiteCollection t: { var siteUrl = tokenParser.ParseString(t.Url); SiteEntity siteInfo = new SiteEntity() { Lcid = (uint)t.Language, Template = "STS#3", TimeZoneId = t.TimeZoneId, Title = tokenParser.ParseString(t.Title), Url = tokenParser.ParseString(t.Url), SiteOwnerLogin = tokenParser.ParseString(t.Owner), }; WriteMessage($"Creating Team Site with no Office 365 group at {siteUrl}", ProvisioningMessageType.Progress); if (tenant.SiteExists(siteUrl)) { WriteMessage($"Using existing Team Site at {siteUrl}", ProvisioningMessageType.Progress); siteContext = (tenant.Context as ClientContext).Clone(siteUrl, applyingInformation.AccessTokens); } else { tenant.CreateSiteCollection(siteInfo, false, true); siteContext = tenant.Context.Clone(siteUrl, applyingInformation.AccessTokens); } if (t.IsHubSite) { RegisterAsHubSite(tenant, siteContext.Url, t.HubSiteLogoUrl); } if (!string.IsNullOrEmpty(t.Theme)) { var parsedTheme = tokenParser.ParseString(t.Theme); tenant.SetWebTheme(parsedTheme, siteContext.Url); tenant.Context.ExecuteQueryRetry(); } siteUrls.Add(t.Id, siteContext.Url); if (!string.IsNullOrEmpty(t.ProvisioningId)) { _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, t.ProvisioningId, siteContext.Url)); siteContext.Web.EnsureProperty(w => w.Id); _additionalTokens.Add(new SequenceSiteIdToken(null, t.ProvisioningId, siteContext.Web.Id)); siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId); _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, t.ProvisioningId, siteContext.Site.Id)); _additionalTokens.Add(new SequenceSiteGroupIdToken(null, t.ProvisioningId, siteContext.Site.GroupId)); } break; } } var web = siteContext.Web; foreach (var subsite in sitecollection.Sites) { var subSiteObject = (TeamNoGroupSubSite)subsite; web.EnsureProperties(w => w.Webs.IncludeWithDefaultProperties(), w => w.ServerRelativeUrl); siteTokenParser = CreateSubSites(hierarchy, siteTokenParser, sitecollection, siteContext, web, subSiteObject); } } // System.Threading.Thread.Sleep(TimeSpan.FromMinutes(10)); WriteMessage("Applying templates", ProvisioningMessageType.Progress); var currentSite = ""; var provisioningTemplateApplyingInformation = new ProvisioningTemplateApplyingInformation(); provisioningTemplateApplyingInformation.AccessTokens = applyingInformation.AccessTokens; provisioningTemplateApplyingInformation.MessagesDelegate = applyingInformation.MessagesDelegate; provisioningTemplateApplyingInformation.ProgressDelegate = (string message, int step, int total) => { applyingInformation.ProgressDelegate?.Invoke($"{currentSite} : {message}", step, total); }; provisioningTemplateApplyingInformation.SiteProvisionedDelegate = applyingInformation.SiteProvisionedDelegate; foreach (var sitecollection in sequence.SiteCollections) { currentSite = sitecollection.ProvisioningId != null ? sitecollection.ProvisioningId : sitecollection.Title; siteUrls.TryGetValue(sitecollection.Id, out string siteUrl); if (siteUrl != null) { using (var clonedContext = tenant.Context.Clone(siteUrl, applyingInformation.AccessTokens)) { var web = clonedContext.Web; foreach (var templateRef in sitecollection.Templates) { var provisioningTemplate = hierarchy.Templates.FirstOrDefault(t => t.Id == templateRef); if (provisioningTemplate != null) { provisioningTemplate.Connector = hierarchy.Connector; //if (siteTokenParser == null) //{ siteTokenParser = new TokenParser(web, provisioningTemplate, applyingInformation); foreach (var token in _additionalTokens) { siteTokenParser.AddToken(token); } //} //else //{ // siteTokenParser.Rebase(web, provisioningTemplate); //} WriteMessage($"Applying Template", ProvisioningMessageType.Progress); new SiteToTemplateConversion().ApplyRemoteTemplate(web, provisioningTemplate, provisioningTemplateApplyingInformation, true, siteTokenParser); } else { WriteMessage($"Referenced template ID {templateRef} not found", ProvisioningMessageType.Error); } } if (siteTokenParser == null) { siteTokenParser = new TokenParser(tenant, hierarchy, applyingInformation); foreach (var token in _additionalTokens) { siteTokenParser.AddToken(token); } } foreach (var subsite in sitecollection.Sites) { var subSiteObject = (TeamNoGroupSubSite)subsite; web.EnsureProperties(w => w.Webs.IncludeWithDefaultProperties(), w => w.ServerRelativeUrl); siteTokenParser = ApplySubSiteTemplates(hierarchy, siteTokenParser, sitecollection, clonedContext, web, subSiteObject, provisioningTemplateApplyingInformation); } } } } } return(tokenParser); } }
public static string CombineAreaFileVirtualPath(string areaName, params string[] paths) { string basePhysicalPath = UrlUtility.Combine("~/", "Areas", areaName); return(UrlUtility.Combine(basePhysicalPath, UrlUtility.Combine(paths))); }
public void CanProvisionObjectsRequiredField() { XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(resourceFolder, ""); var template = provider.GetTemplate(resourceFolder + "/" + fileName); FileSystemConnector connector = new FileSystemConnector(resourceFolder, ""); template.Connector = connector; // replace whatever files is in the template with a file we control template.Files.Clear(); template.Files.Add(new Core.Framework.Provisioning.Model.File() { Overwrite = true, Src = fileName, Folder = "Lists/ProjectDocuments" }); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); new ObjectContentType().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); new ObjectFiles().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); ctx.Web.EnsureProperties(w => w.ServerRelativeUrl); var file = ctx.Web.GetFileByServerRelativeUrl( UrlUtility.Combine(ctx.Web.ServerRelativeUrl, UrlUtility.Combine("Lists/ProjectDocuments", fileName))); ctx.Load(file, f => f.Exists); ctx.ExecuteQueryRetry(); Assert.IsTrue(file.Exists); // cleanup for artifacts specific to this test foreach (var list in template.Lists) { ctx.Web.GetListByUrl(list.Url).DeleteObject(); } foreach (var ct in template.ContentTypes) { ctx.Web.GetContentTypeById(ct.Id).DeleteObject(); } var idsToDelete = new List <Guid>(); foreach (var field in ctx.Web.Fields) { if (field.Group == "My Columns") { idsToDelete.Add(field.Id); } } foreach (var guid in idsToDelete) { ctx.Web.GetFieldById <Microsoft.SharePoint.Client.Field>(guid).DeleteObject(); } ctx.ExecuteQueryRetry(); } }
/// <summary> /// Initializes a new instance of the <see cref="CommerceDataDir" /> class. /// </summary> /// <param name="cmsDir">The CMS dir.</param> public CommerceDataDir(IBaseDir cmsDir) { CMSDir = cmsDir; this.DataPhysicalPath = Path.Combine(cmsDir.Cms_DataBasePath, this.DataDirName); this.DataVirutalPath = UrlUtility.Combine(cmsDir.Cms_DataVirutalPath, this.DataDirName); }
/// <summary> /// Uploads a file to the specified folder, with an optional content type. /// </summary> /// <param name="folder">Folder to upload file to.</param> /// <param name="filePath">Location of the file to be uploaded.</param> /// <param name="contentTypeId">Optional content type; if null (default) the default content type will be used.</param> /// <param name="overwriteIfExists">true (default) to overwite existing files</param> /// <param name="useWebDav">true (default) to save the binary directly (via webdav); false to use file creation</param> /// <returns>The uploaded File, so that additional operations (such as setting properties) can be done.</returns> public static File UploadFile(this Folder folder, string filePath, ContentTypeId contentTypeId = null, bool overwriteIfExists = true, bool useWebDav = true) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentException("File path is required.", "filePath"); } var fileName = System.IO.Path.GetFileName(filePath); LoggingUtility.Internal.TraceInformation((int)EventId.UploadFile, CoreResources.FileFolderExtensions_UploadFile, fileName, filePath); File file = null; if (useWebDav) { if (!folder.IsObjectPropertyInstantiated("ServerRelativeUrl")) { folder.Context.Load(folder, f => f.ServerRelativeUrl); folder.Context.ExecuteQuery(); } var serverRelativeUrl = UrlUtility.Combine(folder.ServerRelativeUrl, fileName); using (var uploadContext = new ClientContext(folder.Context.Url) { Credentials = folder.Context.Credentials }) { using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { LoggingUtility.Internal.TraceVerbose("Save binary direct (via webdav) to '{0}'", serverRelativeUrl); File.SaveBinaryDirect(uploadContext, serverRelativeUrl, fs, overwriteIfExists); folder.Context.ExecuteQuery(); } } file = folder.Files.GetByUrl(serverRelativeUrl); } else { using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { FileCreationInformation fileCreation = new FileCreationInformation(); fileCreation.ContentStream = fs; fileCreation.Url = fileName; fileCreation.Overwrite = overwriteIfExists; LoggingUtility.Internal.TraceVerbose("Creating file info with Url '{0}'", fileCreation.Url); file = folder.Files.Add(fileCreation); folder.Context.ExecuteQuery(); } } if (contentTypeId != null) { LoggingUtility.Internal.TraceVerbose("Setting content type to '{0}'", contentTypeId.StringValue); file.ListItemAllFields["ContentTypeId"] = contentTypeId.StringValue; file.ListItemAllFields.Update(); } return(file); }
protected override void ExecuteCmdlet() { #pragma warning disable CS0618 // Type or member is obsolete SourceUrl = SourceUrl ?? ServerRelativeUrl; #pragma warning restore CS0618 // Type or member is obsolete var webServerRelativeUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!SourceUrl.StartsWith("/")) { SourceUrl = UrlUtility.Combine(webServerRelativeUrl, SourceUrl); } if (!TargetUrl.StartsWith("/")) { TargetUrl = UrlUtility.Combine(webServerRelativeUrl, TargetUrl); } Uri currentContextUri = new Uri(ClientContext.Url); Uri sourceUri = new Uri(currentContextUri, SourceUrl); Uri sourceWebUri = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, sourceUri); Uri targetUri = new Uri(currentContextUri, TargetUrl); Uri targetWebUri = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, targetUri); _sourceContext = ClientContext; if (!currentContextUri.AbsoluteUri.Equals(sourceWebUri.AbsoluteUri, StringComparison.InvariantCultureIgnoreCase)) { _sourceContext = ClientContext.Clone(sourceWebUri); } bool isFile = true; bool srcIsFolder = false; File file = null; Folder folder = null; try { #if ONPREMISES file = _sourceContext.Web.GetFileByServerRelativeUrl(SourceUrl); #else file = _sourceContext.Web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(SourceUrl)); #endif file.EnsureProperties(f => f.Name, f => f.Exists); isFile = file.Exists; } catch { isFile = false; } if (!isFile) { #if ONPREMISES folder = _sourceContext.Web.GetFolderByServerRelativeUrl(SourceUrl); #else folder = _sourceContext.Web.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(SourceUrl)); #endif #if !SP2013 folder.EnsureProperties(f => f.Name, f => f.Exists); srcIsFolder = folder.Exists; #else folder.EnsureProperties(f => f.Name); try { folder.EnsureProperties(f => f.ItemCount); //Using ItemCount as marker if this is a file or folder srcIsFolder = true; } catch { srcIsFolder = false; } #endif } if (Force || ShouldContinue(string.Format(Resources.CopyFile0To1, SourceUrl, TargetUrl), Resources.Confirm)) { var srcWeb = _sourceContext.Web; srcWeb.EnsureProperty(s => s.Url); _targetContext = ClientContext.Clone(targetWebUri.AbsoluteUri); var dstWeb = _targetContext.Web; dstWeb.EnsureProperties(s => s.Url, s => s.ServerRelativeUrl); if (srcWeb.Url == dstWeb.Url) { try { var targetFile = UrlUtility.Combine(TargetUrl, file?.Name); // If src/dst are on the same Web, then try using CopyTo - backwards compability #if ONPREMISES file?.CopyTo(targetFile, OverwriteIfAlreadyExists); #else file?.CopyToUsingPath(ResourcePath.FromDecodedUrl(targetFile), OverwriteIfAlreadyExists); #endif _sourceContext.ExecuteQueryRetry(); return; } catch { SkipSourceFolderName = true; // target folder exist //swallow exception, in case target was a lib/folder which exists } } //different site/site collection Folder targetFolder = null; string fileOrFolderName = null; bool targetFolderExists = false; try { #if ONPREMISES targetFolder = _targetContext.Web.GetFolderByServerRelativeUrl(TargetUrl); #else targetFolder = _targetContext.Web.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(TargetUrl)); #endif #if !SP2013 targetFolder.EnsureProperties(f => f.Name, f => f.Exists); if (!targetFolder.Exists) { throw new Exception("TargetUrl is an existing file, not folder"); } targetFolderExists = true; #else targetFolder.EnsureProperties(f => f.Name); try { targetFolder.EnsureProperties(f => f.ItemCount); //Using ItemCount as marker if this is a file or folder targetFolderExists = true; } catch { targetFolderExists = false; } if (!targetFolderExists) { throw new Exception("TargetUrl is an existing file, not folder"); } #endif } catch (Exception) { targetFolder = null; Expression <Func <List, object> > expressionRelativeUrl = l => l.RootFolder.ServerRelativeUrl; var query = _targetContext.Web.Lists.IncludeWithDefaultProperties(expressionRelativeUrl); var lists = _targetContext.LoadQuery(query); _targetContext.ExecuteQueryRetry(); lists = lists.OrderByDescending(l => l.RootFolder.ServerRelativeUrl); // order descending in case more lists start with the same foreach (List targetList in lists) { if (!TargetUrl.StartsWith(targetList.RootFolder.ServerRelativeUrl, StringComparison.InvariantCultureIgnoreCase)) { continue; } fileOrFolderName = Regex.Replace(TargetUrl, _targetContext.Web.ServerRelativeUrl, "", RegexOptions.IgnoreCase).Trim('/'); targetFolder = srcIsFolder ? _targetContext.Web.EnsureFolderPath(fileOrFolderName) : targetList.RootFolder; //fileOrFolderName = Regex.Replace(TargetUrl, targetList.RootFolder.ServerRelativeUrl, "", RegexOptions.IgnoreCase).Trim('/'); //targetFolder = srcIsFolder ? targetList.RootFolder.EnsureFolder(fileOrFolderName) : targetList.RootFolder; break; } } if (targetFolder == null) { throw new Exception("Target does not exist"); } if (srcIsFolder) { if (!SkipSourceFolderName && targetFolderExists) { targetFolder = targetFolder.EnsureFolder(folder.Name); } CopyFolder(folder, targetFolder); } else { UploadFile(file, targetFolder, fileOrFolderName); } } }
protected override void ExecuteCmdlet() { var serverRelativeUrl = string.Empty; if (string.IsNullOrEmpty(Path)) { Path = SessionState.Path.CurrentFileSystemLocation.Path; } else { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } } var webUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!Url.ToLower().StartsWith(webUrl.ToLower())) { serverRelativeUrl = UrlUtility.Combine(webUrl, Url); } else { serverRelativeUrl = Url; } File file; switch (ParameterSetName) { case URLTOPATH: SaveFileToLocal(SelectedWeb, serverRelativeUrl, Path, Filename, (fileToSave) => { if (!Force) { WriteWarning($"File '{fileToSave}' exists already. use the -Force parameter to overwrite the file."); } return(Force); }); break; case URLASFILEOBJECT: #if ONPREMISES file = SelectedWeb.GetFileByServerRelativeUrl(serverRelativeUrl); #else file = SelectedWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl)); #endif ClientContext.Load(file, f => f.Author, f => f.Length, f => f.ModifiedBy, f => f.Name, f => f.TimeCreated, f => f.TimeLastModified, f => f.Title); ClientContext.ExecuteQueryRetry(); WriteObject(file); break; case URLASLISTITEM: #if ONPREMISES file = SelectedWeb.GetFileByServerRelativeUrl(serverRelativeUrl); #else file = SelectedWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl)); #endif ClientContext.Load(file, f => f.Exists, f => f.ListItemAllFields); ClientContext.ExecuteQueryRetry(); if (file.Exists) { WriteObject(file.ListItemAllFields); } else { if (ThrowExceptionIfFileNotFound) { throw new PSArgumentException($"No file found with the provided Url {serverRelativeUrl}", "Url"); } } break; case URLASSTRING: WriteObject(SelectedWeb.GetFileAsString(serverRelativeUrl)); break; } }
public void CleanUp() { Console.WriteLine("BrandingExtensionsTests.CleanUp"); if (System.IO.File.Exists(customColorFilePath)) { System.IO.File.Delete(customColorFilePath); } if (System.IO.File.Exists(customBackgroundFilePath)) { System.IO.File.Delete(customBackgroundFilePath); } using (var context = TestCommon.CreateClientContext()) { var web = context.Web; // Remove composed looks from server List themeGallery = web.GetCatalog((int)ListTemplateType.DesignCatalog); CamlQuery query = new CamlQuery(); string camlString = @" <View> <Query> <Where> <Contains> <FieldRef Name='Name' /> <Value Type='Text'>Test_</Value> </Contains> </Where> </Query> </View>"; query.ViewXml = camlString; var found = themeGallery.GetItems(query); web.Context.Load(found); web.Context.ExecuteQueryRetry(); Console.WriteLine("{0} matching looks found to delete", found.Count); var looksToDelete = found.ToList(); foreach (var item in looksToDelete) { Console.WriteLine("Delete look item '{0}'", item["Name"]); item.DeleteObject(); context.ExecuteQueryRetry(); } // Remove Theme Files List themesList = web.GetCatalog((int)ListTemplateType.ThemeCatalog); Folder rootFolder = themesList.RootFolder; FolderCollection rootFolders = rootFolder.Folders; web.Context.Load(rootFolder); web.Context.Load(rootFolders, f => f.Where(folder => folder.Name == "15")); web.Context.ExecuteQueryRetry(); Folder folder15 = rootFolders.FirstOrDefault(); try { Microsoft.SharePoint.Client.File customColorFile = folder15.Files.GetByUrl("custom.spcolor"); customColorFile.DeleteObject(); context.ExecuteQueryRetry(); } catch (Exception ex) { Console.WriteLine("Exception cleaning up: {0}", ex); } try { Microsoft.SharePoint.Client.File customBackgroundFile = folder15.Files.GetByUrl("custombg.jpg"); customBackgroundFile.DeleteObject(); context.ExecuteQueryRetry(); } catch (Exception ex) { Console.WriteLine("Exception cleaning up: {0}", ex); } // Remove webs var webCollection1 = web.Webs; context.Load(webCollection1, wc => wc.Include(w => w.Title, w => w.ServerRelativeUrl)); context.ExecuteQueryRetry(); var websToDelete = new List <Web>(); foreach (var web1 in webCollection1) { if (web1.Title.StartsWith("Test_")) { var webCollection2 = web1.Webs; context.Load(webCollection2, wc => wc.Include(w => w.Title, w => w.ServerRelativeUrl)); context.ExecuteQueryRetry(); var childrenToDelete = new List <Web>(webCollection2); foreach (var web2 in childrenToDelete) { Console.WriteLine("Deleting site {0}", web2.ServerRelativeUrl); web2.DeleteObject(); context.ExecuteQueryRetry(); } websToDelete.Add(web1); } } foreach (var web1 in websToDelete) { Console.WriteLine("Deleting site {0}", web1.ServerRelativeUrl); web1.DeleteObject(); try { context.ExecuteQueryRetry(); } catch (Exception ex) { Console.WriteLine("Exception cleaning up: {0}", ex); } } // Remove pagelayouts List masterPageGallery = context.Web.GetCatalog((int)ListTemplateType.MasterPageCatalog); Folder rootFolderInMasterPageGallery = masterPageGallery.RootFolder; context.Load(rootFolderInMasterPageGallery, f => f.ServerRelativeUrl); context.ExecuteQueryRetry(); try { var fileServerRelativeUrl = UrlUtility.Combine(rootFolderInMasterPageGallery.ServerRelativeUrl, publishingPageWithoutExtension); var file = context.Web.GetFileByServerRelativeUrl(String.Format("{0}.aspx", fileServerRelativeUrl)); context.Load(file); context.ExecuteQueryRetry(); file.DeleteObject(); context.ExecuteQueryRetry(); fileServerRelativeUrl = UrlUtility.Combine(rootFolderInMasterPageGallery.ServerRelativeUrl, "test/test", publishingPageWithoutExtension); file = context.Web.GetFileByServerRelativeUrl(String.Format("{0}.aspx", fileServerRelativeUrl)); context.Load(file); context.ExecuteQueryRetry(); file.DeleteObject(); context.ExecuteQueryRetry(); } catch (Exception ex) { Console.WriteLine("Exception cleaning up: {0}", ex); } } Teardown(); }
protected override void ExecuteCmdlet() { if (ParameterSetName == "AsFile") { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } FileName = System.IO.Path.GetFileName(Path); } SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); var folder = SelectedWeb.EnsureFolder(SelectedWeb.RootFolder, Folder); var fileUrl = UrlUtility.Combine(folder.ServerRelativeUrl, FileName); // Check if the file exists if (Checkout) { try { var existingFile = SelectedWeb.GetFileByServerRelativeUrl(fileUrl); existingFile.EnsureProperty(f => f.Exists); if (existingFile.Exists) { SelectedWeb.CheckOutFile(fileUrl); } } catch { // Swallow exception, file does not exist } } Microsoft.SharePoint.Client.File file = null; if (ParameterSetName == "AsFile") { file = folder.UploadFile(FileName, Path, true); } else { file = folder.UploadFile(FileName, Stream, true); } if (Values != null) { var item = file.ListItemAllFields; foreach (var key in Values.Keys) { item[key as string] = Values[key]; } item.Update(); ClientContext.ExecuteQueryRetry(); } if (Checkout) { SelectedWeb.CheckInFile(fileUrl, CheckinType.MajorCheckIn, CheckInComment); } if (Publish) { SelectedWeb.PublishFile(fileUrl, PublishComment); } if (Approve) { SelectedWeb.ApproveFile(fileUrl, ApproveComment); } WriteObject(file); }
private string GetServerRelativeUrl(string url) { var serverRelativeUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); return(UrlUtility.Combine(serverRelativeUrl, url)); }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { // Extract the Home Page web.EnsureProperties(w => w.RootFolder.WelcomePage, w => w.ServerRelativeUrl, w => w.Url); var homepageUrl = web.RootFolder.WelcomePage; if (string.IsNullOrEmpty(homepageUrl)) { homepageUrl = "Default.aspx"; } var welcomePageUrl = UrlUtility.Combine(web.ServerRelativeUrl, homepageUrl); var file = web.GetFileByServerRelativeUrl(welcomePageUrl); try { var listItem = file.EnsureProperty(f => f.ListItemAllFields); if (listItem != null) { if (listItem.FieldValues.ContainsKey("WikiField")) { // Wiki page var fullUri = new Uri(UrlUtility.Combine(web.Url, web.RootFolder.WelcomePage)); var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/'); var fileName = fullUri.Segments[fullUri.Segments.Count() - 1]; var homeFile = web.GetFileByServerRelativeUrl(welcomePageUrl); LimitedWebPartManager limitedWPManager = homeFile.GetLimitedWebPartManager(PersonalizationScope.Shared); web.Context.Load(limitedWPManager); var webParts = web.GetWebParts(welcomePageUrl); var page = new Page() { Layout = WikiPageLayout.Custom, Overwrite = true, Url = Tokenize(fullUri.PathAndQuery, web.Url), }; var pageContents = listItem.FieldValues["WikiField"].ToString(); Regex regexClientIds = new Regex(@"id=\""div_(?<ControlId>(\w|\-)+)"); if (regexClientIds.IsMatch(pageContents)) { foreach (Match webPartMatch in regexClientIds.Matches(pageContents)) { String serverSideControlId = webPartMatch.Groups["ControlId"].Value; try { String serverSideControlIdToSearchFor = String.Format("g_{0}", serverSideControlId.Replace("-", "_")); WebPartDefinition webPart = limitedWPManager.WebParts.GetByControlId(serverSideControlIdToSearchFor); web.Context.Load(webPart, wp => wp.Id, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex ); web.Context.ExecuteQueryRetry(); var webPartxml = TokenizeWebPartXml(web, web.GetWebPartXml(webPart.Id, welcomePageUrl)); page.WebParts.Add(new Model.WebPart() { Title = webPart.WebPart.Title, Contents = webPartxml, Order = (uint)webPart.WebPart.ZoneIndex, Row = 1, // By default we will create a onecolumn layout, add the webpart to it, and later replace the wikifield on the page to position the webparts correctly. Column = 1 // By default we will create a onecolumn layout, add the webpart to it, and later replace the wikifield on the page to position the webparts correctly. }); pageContents = Regex.Replace(pageContents, serverSideControlId, string.Format("{{webpartid:{0}}}", webPart.WebPart.Title), RegexOptions.IgnoreCase); } catch (ServerException) { scope.LogWarning("Found a WebPart ID which is not available on the server-side. ID: {0}", serverSideControlId); } } } page.Fields.Add("WikiField", pageContents); template.Pages.Add(page); // Set the homepage if (template.WebSettings == null) { template.WebSettings = new WebSettings(); } template.WebSettings.WelcomePage = homepageUrl; } else { if (web.Context.HasMinimalServerLibraryVersion(Constants.MINIMUMZONEIDREQUIREDSERVERVERSION)) { // Not a wikipage template = GetFileContents(web, template, welcomePageUrl, creationInfo, scope); if (template.WebSettings == null) { template.WebSettings = new WebSettings(); } template.WebSettings.WelcomePage = homepageUrl; } else { WriteWarning(string.Format("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION), ProvisioningMessageType.Warning); scope.LogWarning("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION); } } } } catch (ServerException ex) { if (ex.ServerErrorCode != -2146232832) { throw; } else { if (web.Context.HasMinimalServerLibraryVersion(Constants.MINIMUMZONEIDREQUIREDSERVERVERSION)) { // Page does not belong to a list, extract the file as is template = GetFileContents(web, template, welcomePageUrl, creationInfo, scope); if (template.WebSettings == null) { template.WebSettings = new WebSettings(); } template.WebSettings.WelcomePage = homepageUrl; } else { WriteWarning(string.Format("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION), ProvisioningMessageType.Warning); scope.LogWarning("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION); } } } // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } return(template); }
internal string ReWriteUrls(string input, string sourceSiteUrl, string sourceWebUrl, string targetWebUrl, string pagesLibrary) { //TODO: find a solution for managed navigation links as they're returned as "https://bertonline.sharepoint.com/sites/ModernizationTarget/_layouts/15/FIXUPREDIRECT.ASPX?WebId=b710de6c-ff13-41f2-b119-0e7ad57269d2&TermSetId=c6eba345-eaf4-4e17-9c3e-c8436e017326&TermId=c2d20b8f-e70b-417d-8aa3-d5e3b59f6167" string origSourceSiteUrl = sourceSiteUrl; string origTargetWebUrl = targetWebUrl; bool isSubSite = !sourceSiteUrl.Equals(sourceWebUrl, StringComparison.InvariantCultureIgnoreCase); // ******************************************************** // Custom URL rewriting logic (if URL mapping was provided) // ******************************************************** if (this.urlMapping != null && this.urlMapping.Count > 0) { foreach (var urlMapping in this.urlMapping) { input = RewriteUrl(input, urlMapping.SourceUrl, urlMapping.TargetUrl); } } if (!this.skipDefaultUrlRewrite) { // ******************************************** // Default URL rewriting logic // ******************************************** // // Root site collection URL rewriting: // http://contoso.com/sites/portal -> https://contoso.sharepoint.com/sites/hr // http://contoso.com/sites/portal/pages -> https://contoso.sharepoint.com/sites/hr/sitepages // /sites/portal -> /sites/hr // /sites/portal/pages -> /sites/hr/sitepages // // If site is a sub site then we also by rewrite the sub URL's // http://contoso.com/sites/portal/hr -> https://contoso.sharepoint.com/sites/hr // http://contoso.com/sites/portal/hr/pages -> https://contoso.sharepoint.com/sites/hr/sitepages // /sites/portal/hr -> /sites/hr // /sites/portal/hr/pages -> /sites/hr/sitepages // Rewrite url's from pages library to sitepages if (!string.IsNullOrEmpty(pagesLibrary)) { string pagesSourceWebUrl = UrlUtility.Combine(sourceWebUrl, pagesLibrary); string sitePagesTargetWebUrl = UrlUtility.Combine(targetWebUrl, "sitepages"); if (pagesSourceWebUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) || pagesSourceWebUrl.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) { input = RewriteUrl(input, pagesSourceWebUrl, sitePagesTargetWebUrl); // Make relative for next replacement attempt pagesSourceWebUrl = MakeRelative(pagesSourceWebUrl); sitePagesTargetWebUrl = MakeRelative(sitePagesTargetWebUrl); } input = RewriteUrl(input, pagesSourceWebUrl, sitePagesTargetWebUrl); } //Ensure the trailing slash if (input != sourceSiteUrl) { sourceWebUrl = $"{sourceWebUrl.TrimEnd('/')}/"; targetWebUrl = $"{targetWebUrl.TrimEnd('/')}/"; } // Rewrite web urls if (sourceWebUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) || sourceWebUrl.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) { input = RewriteUrl(input, sourceWebUrl, targetWebUrl); // Make relative for next replacement attempt sourceWebUrl = $"{MakeRelative(sourceWebUrl).TrimEnd('/')}/"; targetWebUrl = $"{MakeRelative(targetWebUrl).TrimEnd('/')}/"; } input = RewriteUrl(input, sourceWebUrl, targetWebUrl); if (isSubSite) { // reset URLs sourceSiteUrl = origSourceSiteUrl; targetWebUrl = origTargetWebUrl; // Rewrite url's from pages library to sitepages if (!string.IsNullOrEmpty(pagesLibrary)) { string pagesSourceSiteUrl = UrlUtility.Combine(sourceSiteUrl, pagesLibrary); string sitePagesTargetWebUrl = UrlUtility.Combine(targetWebUrl, "sitepages"); if (pagesSourceSiteUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) || pagesSourceSiteUrl.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) { input = RewriteUrl(input, pagesSourceSiteUrl, sitePagesTargetWebUrl); // Make relative for next replacement attempt pagesSourceSiteUrl = MakeRelative(pagesSourceSiteUrl); sitePagesTargetWebUrl = MakeRelative(sitePagesTargetWebUrl); } input = RewriteUrl(input, pagesSourceSiteUrl, sitePagesTargetWebUrl); } // Rewrite root site urls if (sourceSiteUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) || sourceSiteUrl.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) { input = RewriteUrl(input, sourceSiteUrl, targetWebUrl); // Make relative for next replacement attempt sourceSiteUrl = $"{MakeRelative(sourceSiteUrl).TrimEnd('/')}/"; targetWebUrl = $"{MakeRelative(targetWebUrl).TrimEnd('/')}/"; } input = RewriteUrl(input, sourceSiteUrl, targetWebUrl); } } return(input); }