/// <summary> /// List the web parts on a page /// </summary> /// <param name="properties">Information about the site that this method operates on</param> public void GetWebParts(string folder) { UsingContext(ctx => { Site site = ctx.Site; Web web = site.RootWeb; Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder); ctx.Load(pagesLib.Files); ctx.ExecuteQuery(); Microsoft.SharePoint.Client.File ofile = pagesLib.Files[0]; ctx.Load(ofile); ctx.ExecuteQuery(); LimitedWebPartManager limitedWebPartManager = ofile.GetLimitedWebPartManager(PersonalizationScope.Shared); ctx.Load(limitedWebPartManager.WebParts, wps => wps.Include(wp => wp.WebPart.Title, wp => wp.Id)); ctx.ExecuteQuery(); if (limitedWebPartManager.WebParts.Count >= 0) { for (int i = 0; i < limitedWebPartManager.WebParts.Count; i++) { WebPart oWebPart = limitedWebPartManager.WebParts[i].WebPart; Console.WriteLine(oWebPart.Title); Console.WriteLine(limitedWebPartManager.WebParts[i].Id); } } }); }
protected void AddListViewWebPart(ClientContext ctx, Web web, string resourceKey, string title, string zoneId, int order, string listName, bool isCalendar, Assembly assembly) { var list = web.Lists.GetByTitle(listName); ctx.Load(web, w => w.ServerRelativeUrl); ctx.Load(list, l => l.Id, l => l.RootFolder.ServerRelativeUrl); ctx.ExecuteQueryRetry(); var listNameForReplace = list.Id.ToString().ToUpper(); var listId = list.Id.ToString().ToLower(); var webPartXml = Encoding.UTF8.GetString(Utility.GetFile(resourceKey, false, assembly)); //Substring(1) strips off the leading BOM from the file //TODO: find a better solution webPartXml = webPartXml.Replace("{ListName}", listNameForReplace) .Replace("{ListId}", listId) .Replace("{ListUrl}", list.RootFolder.ServerRelativeUrl) .Substring(1); var limitedWebPartManager = File.GetLimitedWebPartManager(PersonalizationScope.Shared); var def = limitedWebPartManager.ImportWebPart(webPartXml); def.WebPart.Title = title; limitedWebPartManager.AddWebPart(def.WebPart, zoneId, order); if (!isCalendar) { GetNewView(ctx, list, title); } }
/// <summary> /// Create matter center page /// </summary> /// <param name="clientContext">SharePoint Client Context</param> /// <param name="destinationFolder">SP folder object</param> /// <param name="fileName">SP Url for web dashboard page</param> /// <param name="helperFileContent">Contents of helper file</param> /// <param name="hasUniquePermissions">Boolean value to check whether user has permissions or not</param> internal static void CreateMatterCenterPage(ClientContext clientContext, Folder destinationFolder, string fileName, string helperFileContent, bool hasUniquePermissions) { FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.Url = fileName; fileInfo.Overwrite = true; fileInfo.Content = CreateWebPartPage(clientContext); Microsoft.SharePoint.Client.File MatterCenterPage = destinationFolder.Files.Add(fileInfo); clientContext.Load(MatterCenterPage); clientContext.ExecuteQuery(); if (hasUniquePermissions) { ListItem MatterCenterPageDetails = MatterCenterPage.ListItemAllFields; clientContext.Load(MatterCenterPageDetails, MatterCenterPageProperties => MatterCenterPageProperties.Id); clientContext.ExecuteQuery(); int id = MatterCenterPageDetails.Id; string listName = ConfigurationManager.AppSettings["SitePagesListName"]; BreakItemPermission(clientContext, listName, id); AssignItemPermission(clientContext, listName, id); } LimitedWebPartManager webPartMgr = MatterCenterPage.GetLimitedWebPartManager(PersonalizationScope.Shared); if (!string.IsNullOrWhiteSpace(helperFileContent)) { //// Add web part WebPartDefinition webPartDefinition = webPartMgr.ImportWebPart(string.Format(CultureInfo.InvariantCulture, contentEditorWebpartMetadata, helperFileContent)); webPartMgr.AddWebPart(webPartDefinition.WebPart, Constants.WebPartZone, Constants.ZoneIndex); } clientContext.ExecuteQuery(); Console.WriteLine(Constants.SuccessProvisionPageMessage + fileName.Substring(fileName.LastIndexOf('/') + 1)); }
public void AddWikiOrPublishingPageWebParts(ClientContext ctx, Web web, string contentFieldName) { var rootWeb = ctx.Site.RootWeb; rootWeb.EnsureProperties(w => w.Url, w => w.ServerRelativeUrl); if (WebParts == null || WebParts.Count == 0) { var pageContent = ListItemFieldValues.Find(p => p.FieldName == contentFieldName)?.Value ?? String.Empty; if (web.ServerRelativeUrl != "/") { File.ListItemAllFields[contentFieldName] = pageContent.Replace("{@WebUrl}", web.Url).Replace("{@WebServerRelativeUrl}", web.ServerRelativeUrl).Replace("{@SiteUrl}", rootWeb.Url).Replace("{@SiteServerRelativeUrl}", rootWeb.ServerRelativeUrl); } else { //In this case the web is the root web File.ListItemAllFields[contentFieldName] = pageContent.Replace("{@WebUrl}", web.Url).Replace("{@WebServerRelativeUrl}", "").Replace("{@SiteUrl}", web.Url).Replace("{@SiteServerRelativeUrl}", ""); } File.ListItemAllFields.Update(); return; } var newIdMappings = new Dictionary <string, string>(); var limitedWebPartManager = File.GetLimitedWebPartManager(PersonalizationScope.Shared); AddWikiOrPublishingContentPageWebParts(ctx, web, rootWeb, newIdMappings, limitedWebPartManager); UpdateWikiOrPublishingContentWithStorageKeys(newIdMappings, web, rootWeb, contentFieldName); LoadWebPartManagerFromSharePoint(ctx, limitedWebPartManager); MoveWebPartsToWikiOrPublishingContentEditorWebPartZone(ctx, newIdMappings, limitedWebPartManager); SetPageListViews(ctx, web, newIdMappings); }
//sourceWebPartId - Used to update the content of the wikipage with new web part id public static bool AddWebPartt(Web web, string serverRelativePageUrl, WebPartEntity webPartEntity, string sourceWebPartId = "") { bool isWebPartAdded = false; try { Microsoft.SharePoint.Client.File webPartPage = web.GetFileByServerRelativeUrl(serverRelativePageUrl); web.Context.Load(webPartPage); web.Context.ExecuteQueryRetry(); LimitedWebPartManager webPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared); WebPartDefinition importedWebPart = webPartManager.ImportWebPart(webPartEntity.WebPartXml); WebPartDefinition webPart = webPartManager.AddWebPart(importedWebPart.WebPart, webPartEntity.WebPartZone, webPartEntity.WebPartIndex); web.Context.Load(webPart); web.Context.ExecuteQuery(); CheckForWikiFieldOrPublishingPageContentAndUpdate(webPart, web, webPartPage, sourceWebPartId); isWebPartAdded = true; } catch (Exception ex) { System.Console.ForegroundColor = System.ConsoleColor.Red; Logger.LogErrorMessage("[AddWebPartt] Exception Message: " + ex.Message); System.Console.ResetColor(); ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, web.Url, "AddWebPart", ex.Message, ex.ToString(), "AddWebPartt()", ex.GetType().ToString()); } return(isWebPartAdded); }
/// <summary> /// Inserts a web part on a web part page /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="webPart">Information about the web part to insert</param> /// <param name="page">Page to add the web part on</param> public static void AddWebPartToWebPartPage(this Web web, WebPartEntity webPart, string page) { //Note: getfilebyserverrelativeurl did not work...not sure why not Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(""); web.Context.Load(pagesLib.Files); web.Context.ExecuteQuery(); Microsoft.SharePoint.Client.File webPartPage = null; foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files) { if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase)) { webPartPage = aspxFile; break; } } if (webPartPage == null) { return; } web.Context.Load(webPartPage); web.Context.ExecuteQuery(); LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared); WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(webPart.WebPartXml); limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, webPart.WebPartZone, webPart.WebPartIndex); web.Context.ExecuteQuery(); }
public void AddWebPartPageWebParts(ClientContext ctx, Web web) { var rootWeb = ctx.Site.RootWeb; rootWeb.EnsureProperties(w => w.Url, w => w.ServerRelativeUrl); var limitedWebPartManager = File.GetLimitedWebPartManager(PersonalizationScope.Shared); var newIdMappings = new Dictionary <string, string>(); //Add from last to first in the zone to //avoid dealing with Sequence var orderedWebParts = WebPartPageZoneMappings.OrderByDescending(zm => zm.Position); foreach (var zoneMapping in orderedWebParts) { var wpXml = WebParts[zoneMapping.WebPartId] .Replace("{@WebUrl}", web.Url) .Replace("{@WebServerRelativeUrl}", web.ServerRelativeUrl != "/" ? web.ServerRelativeUrl : "") .Replace("{@SiteUrl}", rootWeb.Url) .Replace("{@SiteServerRelativeUrl}", rootWeb.ServerRelativeUrl != "/" ? rootWeb.ServerRelativeUrl : ""); //This is a crude way to go about cooercing the version numbers //for files created on SPO/SP2016 for SP2013 on prem //probably valid 99.999% of the time, but if it isn't for you, sorry! if (ctx.ServerLibraryVersion.Major == 15) { wpXml = wpXml.Replace("16.0.0.0", "15.0.0.0"); } var hasListIdToken = wpXml.Contains(@"{@ListId:"); var hasListUrlToken = wpXml.Contains(@"{@ListUrl:"); var listTitle = string.Empty; if (hasListIdToken || hasListUrlToken) { listTitle = wpXml.GetInnerText("{@ListId:", "}"); wpXml = ReplaceListTokens(wpXml, ctx, web, false); } var def = limitedWebPartManager.ImportWebPart(wpXml); def = limitedWebPartManager.AddWebPart(def.WebPart, zoneMapping.ZoneId, 0); ctx.Load(def); ctx.Load(def.WebPart); ctx.ExecuteQueryRetry(); newIdMappings[zoneMapping.WebPartId] = def.Id.ToString().Replace("{", "").Replace("}", "").ToLower(); if (WebPartPageWebPartListViews.ContainsKey(zoneMapping.WebPartId)) { //Fallback code for lack of WebPartPages web service to app identities //Need config to do one or other instead of failing over GetNewView(ctx, zoneMapping.WebPartId, listTitle); } } SetPageListViews(ctx, web, newIdMappings); }
private WebPartDefinition AddWebPart(File webPartPage, string wpXml) { var limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared); var oWebPartDefinition = limitedWebPartManager.ImportWebPart(wpXml); var wpdNew = limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, "wpzMain", 1); webPartPage.Context.Load(wpdNew); webPartPage.Context.ExecuteQueryRetry(); return(wpdNew); }
/// <summary> /// Creates Matter Landing Page on matter creation /// </summary> /// <param name="clientContext">Client Context</param> /// <param name="client">Client object containing Client data</param> /// <param name="matter">Matter object containing Matter data</param> /// <returns>true if success else false</returns> internal static string CreateMatterLandingPage(ClientContext clientContext, Client client, Matter matter) { string response = string.Empty; if (null != clientContext && null != client && null != matter) { try { using (clientContext) { Uri uri = new Uri(client.ClientUrl); Web web = clientContext.Web; FileCreationInformation objFileInfo = new FileCreationInformation(); List sitePageLib = null; //// Create Matter Landing Web Part Page objFileInfo.Url = string.Format(CultureInfo.InvariantCulture, "{0}{1}", matter.MatterGuid, Constants.AspxExtension); response = CreateWebPartPage(sitePageLib, clientContext, objFileInfo, matter, web); if (Constants.TRUE == response) { //// Configure All Web Parts string[] webParts = ConfigureXMLCodeOfWebParts(client, matter, clientContext, sitePageLib, objFileInfo, uri, web); Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", uri.AbsolutePath, Constants.Backslash, ConfigurationManager.AppSettings["MatterLandingPageRepository"].Replace(Constants.SPACE, string.Empty), Constants.Backslash, objFileInfo.Url)); clientContext.Load(file); clientContext.ExecuteQuery(); LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); WebPartDefinition webPartDefinition = null; string[] zones = { Constants.HeaderZone, Constants.TopZone, Constants.RightZone, Constants.TopZone, Constants.RightZone, Constants.RightZone, Constants.FooterZone, Constants.RightZone, Constants.RightZone }; AddWebPart(clientContext, limitedWebPartManager, webPartDefinition, webParts, zones); } else { response = Constants.FALSE; } } } catch (Exception ex) { ////Generic Exception MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ErrorMessage"], "creating Matter Landing page")); MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, "Message: " + ex.Message + "\nStacktrace: " + ex.StackTrace); throw; } return(response); } else { return(string.Format(CultureInfo.InvariantCulture, Constants.ServiceResponse, string.Empty, Constants.MessageNoInputs)); } }
/// <summary> /// List the web parts on a page /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="serverRelativePageUrl">Server relative url of the page containing the webparts</param> public static IEnumerable <WebPartDefinition> GetWebParts(this Web web, string serverRelativePageUrl) { List <WebPartDefinition> webparts = new List <WebPartDefinition>(); Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(serverRelativePageUrl); LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); var query = web.Context.LoadQuery(limitedWebPartManager.WebParts.IncludeWithDefaultProperties(wp => wp.Id, wp => wp.WebPart, wp => wp.WebPart.Title, wp => wp.WebPart.Properties, wp => wp.WebPart.Hidden)); web.Context.ExecuteQuery(); return(query); }
/// <summary> /// Deletes a web part from a page /// </summary> /// <param name="properties">Site to insert the web part on</param> /// <param name="title">Title of the web part that needs to be deleted</param> /// <param name="page">Page to add the web part on</param> public void DeleteWebPart(string folder, string title, string page) { UsingContext(ctx => { Site site = ctx.Site; Web web = site.RootWeb; //Note: getfilebyserverrelativeurl did not work...not sure why not Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder); ctx.Load(pagesLib.Files); ctx.ExecuteQuery(); Microsoft.SharePoint.Client.File webPartPage = null; foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files) { if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase)) { webPartPage = aspxFile; break; } } if (webPartPage == null) { return; } ctx.Load(webPartPage); ctx.ExecuteQuery(); LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared); ctx.Load(limitedWebPartManager.WebParts, wps => wps.Include(wp => wp.WebPart.Title)); ctx.ExecuteQuery(); if (limitedWebPartManager.WebParts.Count >= 0) { for (int i = 0; i < limitedWebPartManager.WebParts.Count; i++) { WebPart oWebPart = limitedWebPartManager.WebParts[i].WebPart; if (oWebPart.Title.Equals(title, StringComparison.InvariantCultureIgnoreCase)) { limitedWebPartManager.WebParts[i].DeleteWebPart(); ctx.ExecuteQuery(); break; } } } }); }
void RegisterJStoWebPart(Web web, string url, string jsPath) { Microsoft.SharePoint.Client.File newFormPageFile = web.GetFileByServerRelativeUrl(url); LimitedWebPartManager limitedWebPartManager = newFormPageFile.GetLimitedWebPartManager(PersonalizationScope.Shared); web.Context.Load(limitedWebPartManager.WebParts); web.Context.ExecuteQuery(); if (limitedWebPartManager.WebParts.Count > 0) { WebPartDefinition webPartDef = limitedWebPartManager.WebParts.FirstOrDefault(); webPartDef.WebPart.Properties["JSLink"] = jsPath; webPartDef.SaveWebPartChanges(); web.Context.ExecuteQuery(); } }
private LimitedWebPartManager TryToGetWebPartManager(ClientContext ctx, File file) { try { var webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); ctx.Load(webPartManager.WebParts, wp => wp.Include(p => p.Id, p => p.WebPart)); ctx.ExecuteQueryRetry(); return(webPartManager); } catch { return(null); } }
public static void AddWebPartToPage(Web web, string webPartFile, Microsoft.SharePoint.Client.File page, string zoneId) { Folder rootFolder = web.RootFolder; web.Context.Load(rootFolder, root => root.WelcomePage, root => root.ServerRelativeUrl); web.Context.ExecuteQueryRetry(); LimitedWebPartManager wpMgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared); XDocument xDoc = XDocument.Load(webPartFile); WebPartDefinition def = wpMgr.ImportWebPart(xDoc.ToString()); WebPartDefinition wpDef = wpMgr.AddWebPart(def.WebPart, zoneId, 0); web.Context.Load(wpDef, wp => wp.Id); web.Context.ExecuteQuery(); }
public void AddWebParts(ClientContext context, File uploadFile, List<ShWebPartReference> webPartReferences, bool replaceWebParts) { // we should be allowed to delete webparts (by using replaceWebparts and define no new ones if (webPartReferences.Count <= 0 && !replaceWebParts) return; var limitedWebPartManager = uploadFile.GetLimitedWebPartManager(PersonalizationScope.Shared); context.Load(limitedWebPartManager, manager => manager.WebParts); context.ExecuteQuery(); if (limitedWebPartManager.WebParts.Count == 0 || replaceWebParts) { for (int i = limitedWebPartManager.WebParts.Count - 1; i >= 0; i--) { limitedWebPartManager.WebParts[i].DeleteWebPart(); } context.ExecuteQuery(); foreach (ShWebPartReference webPart in webPartReferences) { //Convention: All webparts are located in the content/webparts folder var webPartPath = Path.Combine(_contentDirectoryPath, "webparts", webPart.FileName); var webPartFileContent = System.IO.File.ReadAllText(webPartPath); if (!System.IO.File.Exists(webPartPath)) { Log.ErrorFormat("Webpart at path {0} not found", webPartPath); continue; } //Token replacement in the webpart XML webPartFileContent = GetPropertyValueWithTokensReplaced(webPartFileContent, context); var webPartDefinition = limitedWebPartManager.ImportWebPart(webPartFileContent); if (webPart.PropertiesOverrides.Count > 0) { foreach (KeyValuePair<string, string> propertyOverride in webPart.PropertiesOverrides) { //Token replacement in the PropertiesOverrides JSON array var propOverrideValue = GetPropertyValueWithTokensReplaced(propertyOverride.Value, context); webPartDefinition.WebPart.Properties[propertyOverride.Key] = propOverrideValue; } } limitedWebPartManager.AddWebPart(webPartDefinition.WebPart, webPart.ZoneID, webPart.Order); } context.Load(limitedWebPartManager); context.ExecuteQuery(); } }
public void AddWebParts(ClientContext context, File uploadFile, List <ShWebPartReference> webPartReferences, bool replaceWebParts) { // we should be allowed to delete webparts (by using replaceWebparts and define no new ones if (webPartReferences.Count <= 0 && !replaceWebParts) { return; } var limitedWebPartManager = uploadFile.GetLimitedWebPartManager(PersonalizationScope.Shared); context.Load(limitedWebPartManager, manager => manager.WebParts); context.ExecuteQuery(); if (limitedWebPartManager.WebParts.Count == 0 || replaceWebParts) { for (int i = limitedWebPartManager.WebParts.Count - 1; i >= 0; i--) { limitedWebPartManager.WebParts[i].DeleteWebPart(); context.ExecuteQuery(); } foreach (ShWebPartReference webPart in webPartReferences) { //Convention: All webparts are located in the content/webparts folder var webPartPath = Path.Combine(_contentDirectoryPath, "webparts", webPart.FileName); var webPartFileContent = System.IO.File.ReadAllText(webPartPath); if (!System.IO.File.Exists(webPartPath)) { Log.ErrorFormat("Webpart at path {0} not found", webPartPath); continue; } //Token replacement in the webpart XML webPartFileContent = ReplaceTokensInText(webPartFileContent, context); //Overriding DataProviderJSON properties if specified. Need to use different approach (Update XML directly before import) if (webPart.PropertiesOverrides.Count > 0 || webPart.DataProviderJSONOverrides.Count > 0) { webPartFileContent = ReplaceWebPartPropertyOverrides(context, webPart, webPartFileContent); } var webPartDefinition = limitedWebPartManager.ImportWebPart(webPartFileContent); limitedWebPartManager.AddWebPart(webPartDefinition.WebPart, webPart.ZoneID, webPart.Order); context.Load(limitedWebPartManager); context.ExecuteQuery(); } } }
//protected void WithExistingWebPart(ListItem listItem, WebPartDefinition webPartModel, // Action<WebPart, Microsoft.SharePoint.Client.WebParts.WebPartDefinition> action) //{ // WithExistingWebPart(listItem.File, webPartModel, action); //} protected void WithExistingWebPart(File pageFile, WebPartDefinition webPartModel, Action <WebPart, Microsoft.SharePoint.Client.WebParts.WebPartDefinition> action) { var context = pageFile.Context; var webPartManager = pageFile.GetLimitedWebPartManager(PersonalizationScope.Shared); // web part on the page var webpartOnPage = webPartManager.WebParts.Include(wp => wp.Id, wp => wp.WebPart); var webPartDefenitions = context.LoadQuery(webpartOnPage); context.ExecuteQueryWithTrace(); Microsoft.SharePoint.Client.WebParts.WebPartDefinition def = null; var existingWebPart = FindExistingWebPart(webPartDefenitions, webPartModel, out def); action(existingWebPart, def); }
/// <summary> /// Function to update project landing page as per new project name /// </summary> /// <param name="siteContext">Client context</param> /// <param name="projectToUpdate">Details of project to be updated</param> /// <param name="guid">Project GUID</param> /// <param name="calendarStatus">If Calendar is created</param> /// <param name="taskStatus">If task is created</param> /// <param name="rssFeedStatus">If RSS feed is created</param> public static void UpdateProjectLandingPage(ClientContext siteContext, Project projectToUpdate, string guid, bool calendarStatus, bool taskStatus, bool rssFeedStatus, IConfigurationRoot configuration) { int listID = RetrieveItemId(siteContext, Constants.SITE, guid); try { if (-1 != listID) { List list = siteContext.Web.Lists.GetByTitle(Constants.SITE); ListItem listItem = list.GetItemById(listID); siteContext.Load(listItem); Microsoft.SharePoint.Client.File file = listItem.File; listItem["Title"] = projectToUpdate.NewProjectName; listItem.Update(); /// Update stamped project and project GUID on project landing page LimitedWebPartManager wpm = file.GetLimitedWebPartManager(PersonalizationScope.Shared); siteContext.Load(wpm.WebParts, wps => wps.Include(wp => wp.WebPart.Properties, wp => wp.WebPart.Title)); siteContext.ExecuteQuery(); WebPartDefinitionCollection oWebPartDefinition = wpm.WebParts; siteContext.Load(oWebPartDefinition, item => item.Include(li => li.ZoneId, li => li.WebPart, li => li.WebPart.Properties)); siteContext.ExecuteQuery(); foreach (WebPartDefinition zone in oWebPartDefinition) { if (zone.WebPart.Title.ToLower() == "rss viewer") { rssFeedStatus = true; break; } } foreach (WebPartDefinition zone in oWebPartDefinition) { if (("HeaderZone").Equals(zone.ZoneId)) { zone.DeleteWebPart(); break; } } string catalogAssetsPathStyles = configuration.GetSection("General")["CatalogAssetsStyles"]; string sharePointDLLVersion = configuration.GetSection("General")["SharePointDLLVersion"]; string matterLandingcss = configuration.GetSection("General")["ProjectLandingCss"]; string projectLandingAssets = configuration.GetSection("General")["ProjectLandingAssets"]; string projectCenterAssets = configuration.GetSection("General")["ProjectCenterAssets"]; string projectLandingSectionContent = "<div id=\"{0}\"></div>"; string styleTag = "<link href=\"{0}\" type=\"text/css\" rel=\"stylesheet\" />"; string cssLink = string.Format(CultureInfo.InvariantCulture, catalogAssetsPathStyles + matterLandingcss, projectCenterAssets + Constants.FRONTSLASH + projectLandingAssets); string commonCssLink = string.Format(CultureInfo.InvariantCulture, catalogAssetsPathStyles + Constants.COMMONCSS, projectCenterAssets + Constants.FRONTSLASH + Constants.COMMONASSETS); string headerWebPartSection = string.Format(CultureInfo.InvariantCulture, projectLandingSectionContent, Constants.MATTERCENTERHEADER); string projectLandingStampProperties = "var documentLibraryName = \"{0}\", isNewProjectLandingPage = true, documentLibraryGUID=\"{1}\";"; string scriptTagWithContents = "<script type=\"text/javascript\">{0}</script>"; headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, styleTag, cssLink), headerWebPartSection); headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, styleTag, commonCssLink), headerWebPartSection); headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, scriptTagWithContents, string.Format(CultureInfo.InvariantCulture, projectLandingStampProperties, projectToUpdate.NewProjectName, guid)), headerWebPartSection); string headerWebPart = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, headerWebPartSection, sharePointDLLVersion); WebPartDefinition webPartDefinition = null; if (!string.IsNullOrWhiteSpace(headerWebPart)) { LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); webPartDefinition = limitedWebPartManager.ImportWebPart(headerWebPart); limitedWebPartManager.AddWebPart(webPartDefinition.WebPart, "HeaderZone", 1); siteContext.ExecuteQuery(); } // Remove existing web-parts from page and recreate List projectList = siteContext.Web.Lists.GetByTitle(projectToUpdate.NewProjectName); siteContext.Load(projectList, lst => lst.Title, lst => lst.EntityTypeName); siteContext.ExecuteQuery(); DeleteProjectWebparts(siteContext, projectList); CreateOneNote(siteContext, projectList, projectToUpdate.NewProjectName, configuration); if (taskStatus) { CreateWebPart(siteContext, projectList, projectToUpdate.NewProjectName, Constants.TASK, Constants.TASKPANE, 2, configuration); } if (calendarStatus) { CreateWebPart(siteContext, projectList, projectToUpdate.NewProjectName, Constants.CALENDAR, Constants.CALENDARPANE, 3, configuration); } if (rssFeedStatus) { CreateWebPart(siteContext, projectList, projectToUpdate.NewProjectName, Constants.RSSTITLE, Constants.RSSPANE, 4, configuration); CreateWebPart(siteContext, projectList, projectToUpdate.NewProjectName, Constants.RSSFEED, Constants.RSSPANE, 5, configuration); } } else { //frmMain.status.UpdateStatus("Project landing page not found with GUID: " + projectToUpdate.ProjectGUID, MatterCenter.Common.Message.MessageType.Error); } } catch (Exception exception) { throw; } }
/// <summary> /// Add web part to a wiki style page /// </summary> /// <param name="properties">Site to insert the web part on</param> /// <param name="webPart">Information about the web part to insert</param> /// <param name="page">Page to add the web part on</param> /// <param name="row">Row of the wiki table that should hold the inserted web part</param> /// <param name="col">Column of the wiki table that should hold the inserted web part</param> /// <param name="addSpace">Does a blank line need to be added after the web part (to space web parts)</param> public void AddWebPartToWikiPage(string folder, WebPartEntity webPart, string page, int row, int col, bool addSpace) { UsingContext(ctx => { Site site = ctx.Site; Web web = site.RootWeb; //Note: getfilebyserverrelativeurl did not work...not sure why not Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder); ctx.Load(pagesLib.Files); ctx.ExecuteQuery(); Microsoft.SharePoint.Client.File webPartPage = null; foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files) { if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase)) { webPartPage = aspxFile; break; } } if (webPartPage == null) { return; } ctx.Load(webPartPage); ctx.Load(webPartPage.ListItemAllFields); ctx.ExecuteQuery(); string wikiField = (string)webPartPage.ListItemAllFields["WikiField"]; LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared); WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(webPart.WebPartXml); WebPartDefinition wpdNew = limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, "wpz", 0); ctx.Load(wpdNew); ctx.ExecuteQuery(); //HTML structure in default team site home page (W16) //<div class="ExternalClass284FC748CB4242F6808DE69314A7C981"> // <div class="ExternalClass5B1565E02FCA4F22A89640AC10DB16F3"> // <table id="layoutsTable" style="width:100%;"> // <tbody> // <tr style="vertical-align:top;"> // <td colspan="2"> // <div class="ms-rte-layoutszone-outer" style="width:100%;"> // <div class="ms-rte-layoutszone-inner" style="word-wrap:break-word;margin:0px;border:0px;"> // <div><span><span><div class="ms-rtestate-read ms-rte-wpbox"><div class="ms-rtestate-read 9ed0c0ac-54d0-4460-9f1c-7e98655b0847" id="div_9ed0c0ac-54d0-4460-9f1c-7e98655b0847"></div><div class="ms-rtestate-read" id="vid_9ed0c0ac-54d0-4460-9f1c-7e98655b0847" style="display:none;"></div></div></span></span><p> </p></div> // <div class="ms-rtestate-read ms-rte-wpbox"> // <div class="ms-rtestate-read c7a1f9a9-4e27-4aa3-878b-c8c6c87961c0" id="div_c7a1f9a9-4e27-4aa3-878b-c8c6c87961c0"></div> // <div class="ms-rtestate-read" id="vid_c7a1f9a9-4e27-4aa3-878b-c8c6c87961c0" style="display:none;"></div> // </div> // </div> // </div> // </td> // </tr> // <tr style="vertical-align:top;"> // <td style="width:49.95%;"> // <div class="ms-rte-layoutszone-outer" style="width:100%;"> // <div class="ms-rte-layoutszone-inner" style="word-wrap:break-word;margin:0px;border:0px;"> // <div class="ms-rtestate-read ms-rte-wpbox"> // <div class="ms-rtestate-read b55b18a3-8a3b-453f-a714-7e8d803f4d30" id="div_b55b18a3-8a3b-453f-a714-7e8d803f4d30"></div> // <div class="ms-rtestate-read" id="vid_b55b18a3-8a3b-453f-a714-7e8d803f4d30" style="display:none;"></div> // </div> // </div> // </div> // </td> // <td class="ms-wiki-columnSpacing" style="width:49.95%;"> // <div class="ms-rte-layoutszone-outer" style="width:100%;"> // <div class="ms-rte-layoutszone-inner" style="word-wrap:break-word;margin:0px;border:0px;"> // <div class="ms-rtestate-read ms-rte-wpbox"> // <div class="ms-rtestate-read 0b2f12a4-3ab5-4a59-b2eb-275bbc617f95" id="div_0b2f12a4-3ab5-4a59-b2eb-275bbc617f95"></div> // <div class="ms-rtestate-read" id="vid_0b2f12a4-3ab5-4a59-b2eb-275bbc617f95" style="display:none;"></div> // </div> // </div> // </div> // </td> // </tr> // </tbody> // </table> // <span id="layoutsData" style="display:none;">true,false,2</span> // </div> //</div> XmlDocument xd = new XmlDocument(); xd.PreserveWhitespace = true; xd.LoadXml(wikiField); // Sometimes the wikifield content seems to be surrounded by an additional div? XmlElement layoutsTable = xd.SelectSingleNode("div/div/table") as XmlElement; if (layoutsTable == null) { layoutsTable = xd.SelectSingleNode("div/table") as XmlElement; } XmlElement layoutsZoneInner = layoutsTable.SelectSingleNode(string.Format("tbody/tr[{0}]/td[{1}]/div/div", row, col)) as XmlElement; // - space element XmlElement space = xd.CreateElement("p"); XmlText text = xd.CreateTextNode(" "); space.AppendChild(text); // - wpBoxDiv XmlElement wpBoxDiv = xd.CreateElement("div"); layoutsZoneInner.AppendChild(wpBoxDiv); if (addSpace) { layoutsZoneInner.AppendChild(space); } XmlAttribute attribute = xd.CreateAttribute("class"); wpBoxDiv.Attributes.Append(attribute); attribute.Value = "ms-rtestate-read ms-rte-wpbox"; attribute = xd.CreateAttribute("contentEditable"); wpBoxDiv.Attributes.Append(attribute); attribute.Value = "false"; // - div1 XmlElement div1 = xd.CreateElement("div"); wpBoxDiv.AppendChild(div1); div1.IsEmpty = false; attribute = xd.CreateAttribute("class"); div1.Attributes.Append(attribute); attribute.Value = "ms-rtestate-read " + wpdNew.Id.ToString("D"); attribute = xd.CreateAttribute("id"); div1.Attributes.Append(attribute); attribute.Value = "div_" + wpdNew.Id.ToString("D"); // - div2 XmlElement div2 = xd.CreateElement("div"); wpBoxDiv.AppendChild(div2); div2.IsEmpty = false; attribute = xd.CreateAttribute("style"); div2.Attributes.Append(attribute); attribute.Value = "display:none"; attribute = xd.CreateAttribute("id"); div2.Attributes.Append(attribute); attribute.Value = "vid_" + wpdNew.Id.ToString("D"); ListItem listItem = webPartPage.ListItemAllFields; listItem["WikiField"] = xd.OuterXml; listItem.Update(); ctx.ExecuteQuery(); }); }
private WebPartDefinition AddWebPart(Web web, WebPart webPart, File pageFile) { LimitedWebPartManager limitedWebPartManager = pageFile.GetLimitedWebPartManager(PersonalizationScope.Shared); WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(webPart.Contents); WebPartDefinition wpdNew = limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, webPart.Zone, (int)webPart.Order); web.Context.Load(wpdNew, x => x.Id); web.Context.ExecuteQueryRetry(); return wpdNew; }
public bool Validate(PageCollection sourcePages, Microsoft.SharePoint.Client.ClientContext ctx) { int scount = 0; int tcount = 0; Web web = ctx.Web; ctx.Load(web, w => w.Url, w => w.ServerRelativeUrl); ctx.ExecuteQueryRetry(); foreach (var sourcePage in sourcePages) { string pageUrl = sourcePage.Url.ToString(); pageUrl = pageUrl.Replace("{site}", web.ServerRelativeUrl); Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(pageUrl); ctx.Load(file, page => page.ListItemAllFields, page => page.ListItemAllFields.RoleAssignments.Include(roleAsg => roleAsg.Member, roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name))); ctx.ExecuteQueryRetry(); if (file != null) { #region Page - Fields if (sourcePage.Fields.Count > 0) { scount = 0; tcount = 0; string sourceWikifield = sourcePage.Fields["WikiField"].ToString(); string targetwikiField = (string)file.ListItemAllFields["WikiField"]; if (sourceWikifield.Trim() != RemoveHTMLTags(targetwikiField).Trim()) { return(false); } } #endregion #region Page - Webparts if (!ctx.Web.IsNoScriptSite() && sourcePage.WebParts.Count > 0) { LimitedWebPartManager wpm = file.GetLimitedWebPartManager(PersonalizationScope.Shared); ctx.Load(wpm.WebParts, wps => wps.Include(wp => wp.WebPart.Title, wp => wp.WebPart.Properties)); ctx.ExecuteQueryRetry(); if (wpm.WebParts.Count > 0) { foreach (var spwp in sourcePage.WebParts) { scount++; foreach (WebPartDefinition wpd in wpm.WebParts) { if (spwp.Title == wpd.WebPart.Title) { tcount++; //Page - Webpart Properties Microsoft.SharePoint.Client.WebParts.WebPart wp = wpd.WebPart; var isWebPropertiesMatch = CSOMWebPartPropertiesValidation(spwp.Contents, wp.Properties); if (!isWebPropertiesMatch) { return(false); } } else { return(false); } } } if (scount != tcount) { return(false); } } else { return(false); } } #endregion #region Page - Security scount = 0; tcount = 0; if (sourcePage.Security != null && file.ListItemAllFields.RoleAssignments.Count > 0) { bool securityResult = ValidateSecurityCSOM(ctx, sourcePage.Security, file.ListItemAllFields); if (!securityResult) { return(false); } } #endregion } else { return(false); } } return(true); }
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); List pagesLibrary = web.GetPagesLibrary(); var items = pagesLibrary.GetItems(CamlQuery.CreateAllItemsQuery()); web.Context.Load(items, i => i.Include(it => it.DisplayName, it => it.File)); web.Context.ExecuteQuery(); foreach (ListItem listItem in items) { try { //var listItem = file.EnsureProperty(f => f.ListItemAllFields); if (listItem != null) { File file = listItem.File; if (listItem.FieldValues.ContainsKey("WikiField") && listItem.FieldValues["WikiField"] != null) { // Wiki page var fullUri = new Uri(UrlUtility.Combine(new Uri(web.Url).GetLeftPart(UriPartial.Authority), file.ServerRelativeUrl)); var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/'); LimitedWebPartManager limitedWPManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); web.Context.Load(limitedWPManager); var webParts = web.GetWebParts(file.ServerRelativeUrl); 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, file.ServerRelativeUrl)); 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, file.ServerRelativeUrl, creationInfo, scope); if (template.WebSettings == null) { template.WebSettings = new WebSettings(); } template.WebSettings.WelcomePage = homepageUrl; } else { WriteMessage(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 { WriteMessage(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); }
public void AddWebParts(ClientContext context, File uploadFile, List<ShWebPartReference> webPartReferences, bool replaceWebParts) { // we should be allowed to delete webparts (by using replaceWebparts and define no new ones if (webPartReferences.Count <= 0 && !replaceWebParts) return; var limitedWebPartManager = uploadFile.GetLimitedWebPartManager(PersonalizationScope.Shared); context.Load(limitedWebPartManager, manager => manager.WebParts); context.ExecuteQuery(); if (limitedWebPartManager.WebParts.Count == 0 || replaceWebParts) { for (int i = limitedWebPartManager.WebParts.Count - 1; i >= 0; i--) { limitedWebPartManager.WebParts[i].DeleteWebPart(); context.ExecuteQuery(); } foreach (ShWebPartReference webPart in webPartReferences) { //Convention: All webparts are located in the content/webparts folder var webPartPath = Path.Combine(_contentDirectoryPath, "webparts", webPart.FileName); var webPartFileContent = System.IO.File.ReadAllText(webPartPath); if (!System.IO.File.Exists(webPartPath)) { Log.ErrorFormat("Webpart at path {0} not found", webPartPath); continue; } //Token replacement in the webpart XML webPartFileContent = GetPropertyValueWithTokensReplaced(webPartFileContent, context); //Overriding DataProviderJSON properties if specified. Need to use different approach (Update XML directly before import) if (webPart.PropertiesOverrides.Count > 0 || webPart.DataProviderJSONOverrides.Count > 0) { webPartFileContent = ReplaceWebPartPropertyOverrides(context, webPart, webPartFileContent); } var webPartDefinition = limitedWebPartManager.ImportWebPart(webPartFileContent); limitedWebPartManager.AddWebPart(webPartDefinition.WebPart, webPart.ZoneID, webPart.Order); context.Load(limitedWebPartManager); context.ExecuteQuery(); } } }
private void ExtractWikiPage(Microsoft.SharePoint.Client.File file, ProvisioningTemplate template, PnPMonitoredScope scope, ListItem listItem) { scope.LogDebug(String.Format("ExtractWikiPage {0}", file.ServerRelativeUrl)); var fullUri = GetFullUri(web); var page = new Page() { Layout = WikiPageLayout.Custom, Overwrite = true, Url = fullUri.PathAndQuery.TokenizeUrl(web.Url), }; var wikiField = listItem.FieldValues["WikiField"]; var pageContents = wikiField.ToString(); var regexClientIds = new System.Text.RegularExpressions.Regex(@"id=\""div_(?<ControlId>(\w|\-)+)"); if (regexClientIds.IsMatch(pageContents)) { LimitedWebPartManager limitedWPManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); foreach (System.Text.RegularExpressions.Match webPartMatch in regexClientIds.Matches(pageContents)) { String serverSideControlId = webPartMatch.Groups["ControlId"].Value; try { String serverSideControlIdToSearchFor = String.Format("g_{0}", serverSideControlId.Replace("-", "_")); //var webParts = limitedWPManager.WebParts.ToList(); WebPartDefinition webPart = limitedWPManager.WebParts.GetByControlId(serverSideControlIdToSearchFor); if (webPart != null && webPart.Id != null) { 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, file.ServerRelativeUrl)); page.WebParts.Add(new OfficeDevPnP.Core.Framework.Provisioning.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 (PropertyOrFieldNotInitializedException) { scope.LogWarning("Found a WebPart ID which is not available on the server-side. ID: {0}", serverSideControlId); try { web.Context.ExecuteQueryRetry(); } catch { //suppress pending transaction // avoids issues with invalid/corrupted wiki pages } } 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); }
public static void AddPublishingPage(PublishingPage page, ClientContext ctx, Web web) { SPPublishing.PublishingPage publishingPage = web.GetPublishingPage(page.FileName + ".aspx"); RemovePublishingPage(publishingPage, page, ctx, web); web.AddPublishingPage(page.FileName, page.Layout, page.Title, false); //DO NOT Publish here or it will fail if library doesn't enable Minor versions (PnP bug) publishingPage = web.GetPublishingPage(page.FileName + ".aspx"); Microsoft.SharePoint.Client.File pageFile = publishingPage.ListItem.File; pageFile.CheckOut(); if (page.Properties != null && page.Properties.Count > 0) { ctx.Load(pageFile, p => p.Name, p => p.CheckOutType); //need these values in SetFileProperties ctx.ExecuteQuery(); pageFile.SetFileProperties(page.Properties, false); } if (page.WebParts != null && page.WebParts.Count > 0) { Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager mgr = pageFile.GetLimitedWebPartManager(Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared); ctx.Load(mgr); ctx.ExecuteQuery(); AddWebpartsToPublishingPage(page, ctx, mgr); } List pagesLibrary = publishingPage.ListItem.ParentList; ctx.Load(pagesLibrary); ctx.ExecuteQueryRetry(); ListItem pageItem = publishingPage.ListItem; web.Context.Load(pageItem, p => p.File.CheckOutType); web.Context.ExecuteQueryRetry(); if (pageItem.File.CheckOutType != CheckOutType.None) { pageItem.File.CheckIn(String.Empty, CheckinType.MajorCheckIn); } if (page.Publish && pagesLibrary.EnableMinorVersions) { pageItem.File.Publish(String.Empty); if (pagesLibrary.EnableModeration) { pageItem.File.Approve(String.Empty); } } if (page.WelcomePage) { SetWelcomePage(web, pageFile); } ctx.ExecuteQuery(); }
//protected void WithExistingWebPart(ListItem listItem, WebPartDefinition webPartModel, // Action<WebPart, Microsoft.SharePoint.Client.WebParts.WebPartDefinition> action) //{ // WithExistingWebPart(listItem.File, webPartModel, action); //} protected void WithExistingWebPart(File pageFile, WebPartDefinition webPartModel, Action<WebPart, Microsoft.SharePoint.Client.WebParts.WebPartDefinition> action) { var context = pageFile.Context; var webPartManager = pageFile.GetLimitedWebPartManager(PersonalizationScope.Shared); // web part on the page var webpartOnPage = webPartManager.WebParts.Include(wp => wp.Id, wp => wp.WebPart); var webPartDefenitions = context.LoadQuery(webpartOnPage); context.ExecuteQueryWithTrace(); Microsoft.SharePoint.Client.WebParts.WebPartDefinition def = null; var existingWebPart = FindExistingWebPart(webPartDefenitions, webPartModel, out def); action(existingWebPart, def); }
public static void AddCEWP(ClientContext clientContext, string formUrl, string WebPartTitle, string Zone, string contentLink, bool closeDefaultWebPart) { formUrl = formUrl.Replace("//", "/"); contentLink = contentLink.Replace("//", "/"); System.Console.WriteLine(contentLink); Microsoft.SharePoint.Client.File oFile = clientContext.Web.GetFileByServerRelativeUrl(formUrl); LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared); string webpartxml = @"<?xml version='1.0' encoding='utf-8'?> <WebPart xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://schemas.microsoft.com/WebPart/v2'> <Title>" + WebPartTitle + @"</Title> <FrameType>Default</FrameType> <Description /> <IsIncluded>true</IsIncluded> <ZoneID>" + Zone + @"</ZoneID> <PartOrder>0</PartOrder> <FrameState>Normal</FrameState> <Height /> <Width /> <AllowRemove>true</AllowRemove> <AllowZoneChange>true</AllowZoneChange> <AllowMinimize>true</AllowMinimize> <AllowConnect>true</AllowConnect> <AllowEdit>true</AllowEdit> <AllowHide>true</AllowHide> <IsVisible>true</IsVisible> <DetailLink /> <HelpLink /> <HelpMode>Modeless</HelpMode> <Dir>Default</Dir> <PartImageSmall /> <MissingAssembly>Cannot import this Web Part.</MissingAssembly> <PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge> <IsIncludedFilter /> <ContentLink>" + contentLink + @"</ContentLink> <Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly> <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName> <ContentLink xmlns='http://schemas.microsoft.com/WebPart/v2/ContentEditor'>" + contentLink + @"</ContentLink> <Content xmlns='http://schemas.microsoft.com/WebPart/v2/ContentEditor' /> <PartStorage xmlns='http://schemas.microsoft.com/WebPart/v2/ContentEditor' /> </WebPart>" /*The webpart XML */; try { clientContext.Load(limitedWebPartManager.WebParts); clientContext.ExecuteQuery(); if (closeDefaultWebPart) { CloseDefaultWebPart(clientContext, limitedWebPartManager.WebParts); } DeleteWebPart(clientContext, formUrl, WebPartTitle); var wpd = limitedWebPartManager.ImportWebPart(webpartxml); limitedWebPartManager.AddWebPart(wpd.WebPart, Zone, 0); clientContext.ExecuteQuery(); } catch (Exception ex) { System.Console.WriteLine("error while adding the web part to the {0} form", formUrl); System.Console.WriteLine(ex.Message); } }
public static void GetWebPartUsage(string webPartType, string webUrl, string outPutDirectory) { string exceptionCommentsInfo1 = string.Empty; ClientContext clientContext = null; bool headerWebPart = false; Web web = null; bool isfound = false; string webPartUsageFileName = outPutDirectory + "\\" + Constants.WEBPART_USAGE_ENTITY_FILENAME + timeStamp + Constants.CSVExtension; try { Logger.LogInfoMessage("[GetWebPartUsage] Finding WebPartUsage details for Web Part: " + webPartType + " in Web: " + webUrl); using (ClientContext userContext = Helper.CreateAuthenticatedUserContext(Program.AdminDomain, Program.AdminUsername, Program.AdminPassword, webUrl)) { web = userContext.Web; userContext.Load(web); userContext.ExecuteQuery(); clientContext = userContext; WebPartUsageEntity webPartUsageEntity = null; List <WebPartUsageEntity> webPartUsage = new List <WebPartUsageEntity>(); //Prepare Exception Comments exceptionCommentsInfo1 = "Web Url: " + clientContext.Web.Url + ", Web Part Type: " + webPartType; if (clientContext != null) { List list = AddWebPart.GetPageList(ref clientContext); if (list != null) { var items = list.GetItems(CamlQuery.CreateAllItemsQuery()); //make sure to include the File on each Item fetched clientContext.Load(items, i => i.Include( item => item.File, item => item["EncodedAbsUrl"])); clientContext.ExecuteQuery(); // Iterate through all available pages in the pages list foreach (var item in items) { try { Microsoft.SharePoint.Client.File page = item.File; String pageUrl = page.ServerRelativeUrl;// item.FieldValues["EncodedAbsUrl"].ToString(); Logger.LogInfoMessage("[GetWebPartUsage] Checking for the Web Part on the Page: " + page.Name); // Requires Full Control permissions on the Web LimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared); clientContext.Load(webPartManager, wpm => wpm.WebParts, wpm => wpm.WebParts.Include( wp => wp.WebPart.Hidden, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Properties, wp => wp.WebPart.Subtitle, wp => wp.WebPart.Title, wp => wp.WebPart.TitleUrl, wp => wp.WebPart.ZoneIndex)); clientContext.ExecuteQuery(); foreach (WebPartDefinition webPartDefinition in webPartManager.WebParts) { Microsoft.SharePoint.Client.WebParts.WebPart webPart = webPartDefinition.WebPart; string webPartPropertiesXml = GetWebPartPropertiesServiceCall(clientContext, webPartDefinition.Id.ToString(), pageUrl); string WebPartTypeName = string.Empty; if (webPartPropertiesXml.Contains("WebPart/v2")) { XmlDataDocument xmldoc = new XmlDataDocument(); xmldoc.LoadXml(webPartPropertiesXml); WebPartTypeName = xmldoc.DocumentElement.GetElementsByTagName("TypeName").Item(0).FirstChild.Value; xmldoc = null; } else { webParts webPartProp = null; byte[] byteArray = Encoding.UTF8.GetBytes(webPartPropertiesXml); using (MemoryStream stream = new MemoryStream(byteArray)) { StreamReader streamReader = new StreamReader(stream); System.Xml.XmlReader reader = new XmlTextReader(streamReader); XmlSerializer serializer = new XmlSerializer(typeof(webParts)); webPartProp = (webParts)serializer.Deserialize(reader); WebPartTypeName = webPartProp.webPart.metaData.type.name; stream.Flush(); } byteArray = null; } string actualWebPartType = AddWebPart.GetWebPartShortTypeName(WebPartTypeName); // only modify if we find the old web part if (actualWebPartType.Equals(webPartType, StringComparison.CurrentCultureIgnoreCase)) { Logger.LogInfoMessage("[GetWebPartUsage] Found WebPart: " + webPartType + " in Page: " + page.Name); webPartUsageEntity = new WebPartUsageEntity(); webPartUsageEntity.PageUrl = pageUrl; webPartUsageEntity.WebPartID = webPartDefinition.Id.ToString(); webPartUsageEntity.WebURL = webUrl; webPartUsageEntity.WebPartTitle = webPart.Title; webPartUsageEntity.ZoneIndex = webPart.ZoneIndex.ToString(); webPartUsageEntity.WebPartType = actualWebPartType; FileUtility.WriteCsVintoFile(webPartUsageFileName, webPartUsageEntity, ref headerWebPart); isfound = true; } } } catch (Exception ex) { ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "WebPartUsage", ex.Message, ex.ToString(), "GetWebPartUsage()", ex.GetType().ToString(), exceptionCommentsInfo1); Logger.LogErrorMessage("[GetWebPartUsage] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1); System.Console.ForegroundColor = System.ConsoleColor.Red; Logger.LogErrorMessage("[GetWebPartUsage] Exception Message: " + ex.Message); System.Console.ResetColor(); } } } } //Default Pages GetWebPartUsage_DefaultPages(webPartType, clientContext, outPutDirectory); //Default Pages if (isfound) { Logger.LogSuccessMessage("[GetWebPartUsage] WebPart Usage is exported to the file " + webPartUsageFileName, true); } } } catch (Exception ex) { ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, webUrl, "WebPartUsage", ex.Message, ex.ToString(), "GetWebPartUsage()", ex.GetType().ToString(), exceptionCommentsInfo1); Logger.LogErrorMessage("[GetWebPartUsage] Exception Message: " + ex.Message + ", Exception Comment: " + exceptionCommentsInfo1); System.Console.ForegroundColor = System.ConsoleColor.Red; Logger.LogErrorMessage("[GetWebPartUsage] Exception Message: " + ex.Message); System.Console.ResetColor(); } }
public static void SetSupportCaseContent(ClientContext ctx, string pageName, string url, string queryurl) { List pages = ctx.Web.Lists.GetByTitle("Pages"); ctx.Load(pages.RootFolder, f => f.ServerRelativeUrl); ctx.ExecuteQuery(); Microsoft.SharePoint.Client.File file = ctx.Web.GetFileByServerRelativeUrl(pages.RootFolder.ServerRelativeUrl + "/" + pageName + ".aspx"); ctx.Load(file); ctx.ExecuteQuery(); file.CheckOut(); LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); string quicklaunchmenuFormat = @"<div><a href='{0}/{1}'>Sample Home Page</a></div> <br /> <div style='font-weight:bold'>CSR Dashboard</div> <div class='cdsm_mainmenu'> <ul> <li><a href='{0}/CSRInfo/{1}'>My CSR Info</a></li> <li><a href='{0}/CallQueue/{1}'>Call Queue</a></li> <li> <span class='collapse_arrow'></span> <span><a href='{0}/CustomerDashboard/{1}'>Customer Dashboard</a></span> <ul> <li><a href='{0}/CustomerDashboard/Orders{1}'>Recent Orders</a></li> <li><a class='current' href='#'>Support Cases</a></li> <li><a href='{0}/CustomerDashboard/Notes{1}'>Notes</a></li> </ul> </li> </ul> </div> <div class='cdsm_submenu'> </div>"; string quicklaunchmenu = string.Format(quicklaunchmenuFormat, url, queryurl); string qlwebPartXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><webParts><webPart xmlns=\"http://schemas.microsoft.com/WebPart/v3\"><metaData><type name=\"Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" /><importErrorMessage>Cannot import this Web Part.</importErrorMessage></metaData><data><properties><property name=\"Content\" type=\"string\"><![CDATA[" + quicklaunchmenu + "]]></property><property name=\"ChromeType\" type=\"chrometype\">None</property></properties></data></webPart></webParts>"; WebPartDefinition qlWpd = limitedWebPartManager.ImportWebPart(qlwebPartXml); WebPartDefinition qlWpdNew = limitedWebPartManager.AddWebPart(qlWpd.WebPart, "SupportCasesZoneLeft", 0); ctx.Load(qlWpdNew); //Customer Dropdown List Script Web Part string dpwebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/CustomerDropDownlist.webpart"); WebPartDefinition dpWpd = limitedWebPartManager.ImportWebPart(dpwebPartXml); WebPartDefinition dpWpdNew = limitedWebPartManager.AddWebPart(dpWpd.WebPart, "SupportCasesZoneTop", 0); ctx.Load(dpWpdNew); //Support Case CBS Info Web Part string cbsInfoWebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/SupportCaseCBSWebPartInfo.webpart"); WebPartDefinition cbsInfoWpd = limitedWebPartManager.ImportWebPart(cbsInfoWebPartXml); WebPartDefinition cbsInfoWpdNew = limitedWebPartManager.AddWebPart(cbsInfoWpd.WebPart, "SupportCasesZoneMiddle", 0); ctx.Load(cbsInfoWpdNew); //Support Case Content By Search Web Part string cbswebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/SupportCase CBS Webpart/SupportCaseCBS.webpart"); WebPartDefinition cbsWpd = limitedWebPartManager.ImportWebPart(cbswebPartXml); WebPartDefinition cbsWpdNew = limitedWebPartManager.AddWebPart(cbsWpd.WebPart, "SupportCasesZoneMiddle", 1); ctx.Load(cbsWpdNew); //Support Cases App Part string appPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/SupportCaseAppPart.webpart"); WebPartDefinition appPartWpd = limitedWebPartManager.ImportWebPart(appPartXml); WebPartDefinition appPartdNew = limitedWebPartManager.AddWebPart(appPartWpd.WebPart, "SupportCasesZoneBottom", 0); ctx.Load(appPartdNew); //Get Host Web Query String and show support case list web part string querywebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/GetHostWebQueryStringAndShowList.webpart"); WebPartDefinition queryWpd = limitedWebPartManager.ImportWebPart(querywebPartXml); WebPartDefinition queryWpdNew = limitedWebPartManager.AddWebPart(queryWpd.WebPart, "SupportCasesZoneBottom", 1); ctx.Load(queryWpdNew); file.CheckIn("Data storage model", CheckinType.MajorCheckIn); file.Publish("Data storage model"); ctx.Load(file); ctx.ExecuteQuery(); }