public void Process(WebPartDefinition wpDefinition, File webPartPage) { var web = GetWeb(webPartPage); var list = GetList(web); if (list == null) { return; } var xsltHiddenView = list.GetViewById(wpDefinition.Id); if (xsltHiddenView == null) { return; } var listView = GetViewFromSchemaProperties(list); if (listView == null) { UpdateHiddenViewFromWebPartSchema(xsltHiddenView); } else { UpdateHiddenView(xsltHiddenView, listView.ListViewXml); } }
public WebPartEntity(WebPartDefinition definition) { _id = definition.Id; _hidden = definition.WebPart.Hidden; _subtitle = definition.WebPart.Subtitle; _title = definition.WebPart.Title; _titleurl = definition.WebPart.TitleUrl; _zoneindex = definition.WebPart.ZoneIndex; _properties = definition.WebPart.Properties; }
/// <summary> /// Adds all web parts on matter landing page. /// </summary> /// <param name="clientContext">Client Context</param> /// <param name="limitedWebPartManager">LimitedWebPartManager object to import web parts</param> /// <param name="webPartDefinition">WebPartDefinition object to add web parts on page</param> /// <param name="webParts">Array of web parts that should be added on Matter Landing Page</param> /// <param name="zones">Array of Zone IDs</param> /// <returns>Success flag</returns> public bool AddWebPart(ClientContext clientContext, LimitedWebPartManager limitedWebPartManager, WebPartDefinition webPartDefinition, string[] webParts, string[] zones) { bool result = false; if (null != clientContext && null != limitedWebPartManager && null != webParts && null != zones) { int index = 0; try { for (index = 0; index < webParts.Length; index++) { if (!string.IsNullOrWhiteSpace(webParts[index])) { webPartDefinition = limitedWebPartManager.ImportWebPart(webParts[index]); limitedWebPartManager.AddWebPart(webPartDefinition.WebPart, zones[index], ServiceConstants.ZONE_INDEX); clientContext.ExecuteQuery(); } } } catch (Exception) { result = false; } } return result; }
/// <summary> /// Adding All Web Parts on Matter Landing Page /// </summary> /// <param name="clientContext">SharePoint Client Context</param> /// <param name="limitedWebPartManager">LimitedWebPartManager object to import web parts</param> /// <param name="webPartDefinition">WebPartDefinition object to add web parts on page.</param> /// <param name="webParts">Array of web parts that should be added on Matter Landing Page</param> /// <param name="zones">Array of Zone IDs</param> /// <returns>true if success else false</returns> internal static string AddWebPart(ClientContext clientContext, LimitedWebPartManager limitedWebPartManager, WebPartDefinition webPartDefinition, string[] webParts, string[] zones) { int index = 0; int ZoneIndex = 1; for (index = 0; index < webParts.Length; index++) { if (!string.IsNullOrWhiteSpace(webParts[index])) { webPartDefinition = limitedWebPartManager.ImportWebPart(webParts[index]); limitedWebPartManager.AddWebPart(webPartDefinition.WebPart, zones[index], ZoneIndex); clientContext.ExecuteQuery(); } } return Constants.TRUE; }
//Used to update the content of the wikipage/PublishingPageContent with new web part id [Fix for BugId - 95007] private void CheckForWikiFieldOrPublishingPageContentAndUpdate(WebPartDefinition webPart, Web web, Microsoft.SharePoint.Client.File webPartPage, string sourceWebPartId = "") { string marker = String.Format(System.Globalization.CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div id=\"vid_{0}\"></div></div>", webPart.Id); ListItem item = webPartPage.ListItemAllFields; web.Context.Load(item); web.Context.ExecuteQuery(); FieldUserValue modifiedby = (FieldUserValue)item["Editor"]; FieldUserValue createdby = (FieldUserValue)item["Author"]; DateTime modifiedDate = DateTime.SpecifyKind( DateTime.Parse(item["Modified"].ToString()), DateTimeKind.Utc); DateTime createdDate = DateTime.SpecifyKind( DateTime.Parse(item["Created"].ToString()), DateTimeKind.Utc); item["Editor"] = modifiedby.LookupId; item["Author"] = createdby.LookupId; item["Modified"] = modifiedDate; item["Created"] = createdDate; try { if (item["WikiField"] != null) { string markerToBeUpdated = item["WikiField"].ToString(); if (!string.IsNullOrEmpty(sourceWebPartId)) { string updatedWikiField = markerToBeUpdated.Replace(sourceWebPartId, webPart.Id.ToString()); if (!markerToBeUpdated.Equals(updatedWikiField)) { item["WikiField"] = updatedWikiField; } } else { string parentTag = markerToBeUpdated.Substring(markerToBeUpdated.LastIndexOf("<div class=\"ExternalClass"), (markerToBeUpdated.IndexOf("<div class=\"ExternalClass") + markerToBeUpdated.IndexOf("\">")) + 2); int strPos = markerToBeUpdated.IndexOf(parentTag) + parentTag.Length; StringBuilder markerOfAllWebparts = new StringBuilder(); markerOfAllWebparts.AppendLine(markerToBeUpdated.Substring(0, strPos)); markerOfAllWebparts.AppendLine(marker); markerOfAllWebparts.AppendLine(markerToBeUpdated.Substring(strPos, (markerToBeUpdated.Length - strPos))); item["WikiField"] = markerOfAllWebparts.ToString(); } } } catch { try { if (item["PublishingPageContent"] != null) { string markerToBeUpdated = item["PublishingPageContent"].ToString(); if (!string.IsNullOrEmpty(sourceWebPartId)) { string updatedWikiField = markerToBeUpdated.Replace(sourceWebPartId, webPart.Id.ToString()); if (!markerToBeUpdated.Equals(updatedWikiField)) { item["PublishingPageContent"] = updatedWikiField; } } else { item["PublishingPageContent"] = markerToBeUpdated + marker; } } } catch { //do nothing } } item.Update(); web.Context.ExecuteQuery(); }
public void Process(WebPartDefinition wpDefinition, File webPartPage) { }
protected override void OnBeforeDeployModel(WebpartPageModelHost host, WebPartDefinition webpartModel) { var typedModel = webpartModel.WithAssertAndCast <DocumentSetContentsWebPartDefinition>("webpartModel", value => value.RequireNotNull()); typedModel.WebpartType = typeof(DocumentSetContentsWebPart).AssemblyQualifiedName; }
protected virtual void OnBeforeDeployModel(WebpartPageModelHost host, WebPartDefinition webpartPageModel) { }
public SPOWebPartDefinition(WebPartDefinition webPartDefinition) { _webPartDefinition = webPartDefinition; }
/// <summary> /// Method to process webpart when it is not resolved /// </summary> /// <param name="wpDefinition">WebPartDefinition object</param> /// <param name="webPartPage">File object</param> public void Process(WebPartDefinition wpDefinition, File webPartPage) { }
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); }
/// <summary> /// Add web part to a wiki style page /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="folder">System name of the wiki page library - typically sitepages</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 static void AddWebPartToWikiPage(this Web web, string folder, WebPartEntity webPart, string page, int row, int col, bool addSpace) { //Note: getfilebyserverrelativeurl did not work...not sure why not Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder); 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.Load(webPartPage.ListItemAllFields); web.Context.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); web.Context.Load(wpdNew); web.Context.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(); web.Context.ExecuteQuery(); }
protected void btnAddToPage_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { //get the web part page (DevHome.aspx) which is specific to a developer site template var list = clientContext.Web.Lists.GetByTitle("Site Pages"); CamlQuery camlQuery = new CamlQuery(); var items = list.GetItems(camlQuery); clientContext.Load(items, i => i.Include(item => item.DisplayName, item => item["WikiField"]).Where(item => item.DisplayName == "DevHome")); clientContext.ExecuteQuery(); //get the webpart xml string wpXML = ""; using (var stream = System.IO.File.OpenRead(Server.MapPath("~/MyPicWebPart.dwp"))) { XDocument xdoc = XDocument.Load(stream); wpXML = xdoc.ToString(); wpXML = wpXML.Replace("\r\n", ""); } //add the webpart to the page var wikiPage = items[0].File; LimitedWebPartManager limitedWebPartManager = wikiPage.GetLimitedWebPartManager(PersonalizationScope.Shared); WebPartDefinition wpd = limitedWebPartManager.ImportWebPart(wpXML); var newWP = limitedWebPartManager.AddWebPart(wpd.WebPart, "wpz", 0); clientContext.Load(newWP); clientContext.ExecuteQuery(); // Create reference to WebPart in HTML string wikiField = items[0]["WikiField"] as string; XmlDocument xd = new XmlDocument(); xd.PreserveWhitespace = true; xd.LoadXml(wikiField); XmlElement layoutsZoneInner = xd.SelectSingleNode("div/table/tbody/tr/td/div/div") as XmlElement; //create wrapper XmlElement wpWrapper = xd.CreateElement("div"); layoutsZoneInner.AppendChild(wpWrapper); XmlAttribute attribute = xd.CreateAttribute("class"); wpWrapper.Attributes.Append(attribute); attribute.Value = "ms-rtestate-read ms-rte-wpbox"; //create inner elements XmlElement div1 = xd.CreateElement("div"); wpWrapper.AppendChild(div1); div1.IsEmpty = false; attribute = xd.CreateAttribute("class"); div1.Attributes.Append(attribute); attribute.Value = "ms-rtestate-notify ms-rtestate-read " + newWP.Id.ToString("D"); attribute = xd.CreateAttribute("id"); div1.Attributes.Append(attribute); attribute.Value = "div_" + newWP.Id.ToString("D"); XmlElement div2 = xd.CreateElement("div"); wpWrapper.AppendChild(div2); div2.IsEmpty = false; attribute = xd.CreateAttribute("class"); div2.Attributes.Append(attribute); attribute.Value = "ms-rtestate-read"; attribute = xd.CreateAttribute("style"); div2.Attributes.Append(attribute); attribute.Value = "display:none"; attribute = xd.CreateAttribute("id"); div2.Attributes.Append(attribute); attribute.Value = "vid_" + newWP.Id.ToString("D"); // Update items[0]["WikiField"] = xd.OuterXml; items[0].Update(); clientContext.ExecuteQuery(); //toggle the UI imgWPP.ImageUrl = "~/Images/Yes.png"; btnAddToPage.Enabled = false; } }
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 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(); }