• This email address is being protected from spambots. You need JavaScript enabled to view it.

    Recent items


This is an easy example to add a WebParts (in my case a Summary Link WebPart) into a RichHTML field hosted into a publishing page by a console application.

Custom summary link WP

In my example, I use a the Summary Link WebPart and modify at runtime the XSL styles. The webpart is already deployed and it's available under WebPart Gallery.

During the envelope of my console application, I encurred in some errors. One of this was "Object reference not set to an instance of an object" when I add the webpart to the page. This error encurred because I define a differnt XSL.

To apply the XSL, the system needs of the SPContext for the Item (that's null in a console application). So, from line 53th to 59th I had to initialize the context and at the end of the main, I had to put it null.

Reset the Context is foundamental if you use this code under a foreach that create or modify some pages. During my tests, if I did not reset the context, the first page was created correctly but whe I was to create the others, I encourred into an "Access denied" error.

To add the WP into the publishing page, you first must add it into wpz publishing web part zone and after put the marker that reference the web part into the RichHTML field (you can see that from 90th to 102th line).

Show/Hidden csharp code

View source
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Collections;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Publishing;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Xml;
using Microsoft.SharePoint.Publishing.Fields;
using System.Globalization;
using Microsoft.SharePoint.Publishing.WebControls;
using System.Web;
namespace com.lucacostante
    class Program
        static void Main(string[] args)
            string mySiteUrl = "";
            using (SPSite site = new SPSite(mySiteUrl))
                SPWeb web = site.RootWeb;
                if (web != null)
                    PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);
                    PublishingPage page = pWeb.GetPublishingPage("/Pages/default.aspx");
                    System.Web.UI.WebControls.WebParts.WebPart webPart = null;
                    // access webparts
                    SPList webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
                    SPLimitedWebPartManager wpMgr = web.GetLimitedWebPartManager(page.Uri.ToString(), PersonalizationScope.Shared);
                    SPListItem wp = (from SPListItem item in webPartGallery.Items
                                     where item.Title == "Summary Links"
                                     select item).FirstOrDefault();
                    if (wp != null)
                        XmlReader xmlReader = new XmlTextReader(wp.File.OpenBinaryStream());
                        string errorMessage;
                        webPart = wpMgr.ImportWebPart(xmlReader, out errorMessage);
                    // to modify XSL link, with console application you must initialize the context, 
                    // otherwise you have "Object reference not set to an instance of an object" error ..
                    if (HttpContext.Current == null)
                        HttpRequest request = new HttpRequest("", web.Url, "");
                        HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
                        HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
                    //test cust
                    SummaryLinkWebPart customSlwp = (SummaryLinkWebPart)webPart;
                    customSlwp.ItemContext = SPContext.Current;
                    customSlwp.HeaderXslLink = "/Style Library/XSL Style Sheets/CustomSummaryLinkHeader.xsl";
                    customSlwp.MainXslLink = "/Style Library/XSL Style Sheets/CustomSummaryLinkLinkMain.xsl";
                    customSlwp.ItemXslLink = "/Style Library/XSL Style Sheets/CustomSummaryLinkItemStyle.xsl";
                    //here add links to WP
                    SummaryLinkFieldValue fieldValue = new SummaryLinkFieldValue(customSlwp.SummaryLinkStore);
                    var link = new SummaryLink("test.doc");
                    link.LinkUrl = "";
                    customSlwp.SummaryLinkStore = fieldValue.ToString();
                    link = new SummaryLink("test2.doc");
                    link.LinkUrl = "";
                    customSlwp.SummaryLinkStore = fieldValue.ToString();
                    link = new SummaryLink("test3.pdf");
                    link.LinkUrl = "";
                    customSlwp.SummaryLinkStore = fieldValue.ToString();
                    // check out page before making changes
                    Guid storageKey = Guid.NewGuid();
                    string wpId = String.Format("g_{0}", storageKey.ToString().Replace('-', '_'));
                    customSlwp.ID = wpId;
                    customSlwp.Title = "Custom Summary Link WebPart into Rich-HTML field";
                    wpMgr.AddWebPart(customSlwp, "wpz", 0); //this wpzone is added automatically into a publishing page
                    string marker = String.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\">"+
                        "<div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"></div></div>", 
                        new object[] { storageKey.ToString("D") });
                    SPListItem pageItem = page.ListItem;
                    string content = pageItem["BodyHTML"] as string;
                    pageItem["BodyHTML"] = string.Join("", new string[] { content, marker });
                    page.CheckIn("Added SummaryLink WP");
                    //here must to set a null the httpcontext, otherwise if you have this part of code into a loop that modify or create page, 
                    //you have Exception from HRESULT: 0x8107026E error!
                    HttpContext.Current = null;

Published in SharePoint