Monthly Archives: July 2010

RCWP Part 3 – Edit Web Part using a Ribbon modal dialog

Also check out the other part of the series:

This follows on from Part 1 (where we created a “Related Content Web Part”) and Part 2 (where we added a contextual tab to the Ribbon).

This post summarised the final part of this Web Part (which we completed in the final session of the day of SPRetreat last Saturday).

We wanted to provide a pop-up window, accessed through our new Contextual Tab in the Ribbon, which allowed us to easily modify some web part properties.

The basis of this was quite straight-forward, and it certainly starts off quite easy.
We created a new Application Page (RCWP_SetFieldValue.aspx) which would contain the code to update our Web Part Properties.

In this file we added a simple ASP.Net Label, Drop Down List and button.

<asp:Content ID=”Main” ContentPlaceHolderID=”PlaceHolderMain” runat=”server”>
    This allows you to set the field value for the <strong>Related Content Web Part</strong>
<asp:Label runat=”server” ID=”lblChoice” Text=”Select Field:” AssociatedControlID=”ddlFields” /><br />
<asp:DropDownList runat=”server” ID=”ddlFields” /><br />
<asp:Button runat=”server” ID=”btnNike” Text=”Just Do It!” />

Back in Part 2 we created a JavaScript file which was use for the “Command” events for our Buttons (yes .. I told you we’d be looking at that again!).

Here we are going to modify one of the Buttons so that it throws up a SharePoint Modal Dialog with our Application Page in it.

The code below is modified from the original MS Blog Article I referenced in Part 2 (called “How to create a Web Part with a Contextual Tab”).

if (commandId === ‘CustomContextualTab.GoodbyeWorldCommand’) {
            //alert(‘Good-bye, world!’);
            var options = {
                url: ‘/_layouts/SPR3/RCWP_SetFieldValue.aspx,
                title: ‘Set Field’,
                allowMaximize: false,
                showClose: true,
                width: 800,
                height: 600

I have basically changed the JavaScript for the “GoodbyeWorldCommand” button so that it does something different.

I am using the new SP.UI.ModalDialog namespace in the SharePoint ECMAScript to pop up a modal dialog window.

(Note – I also changed the display text to “Set Field” .. and deleted the other button to clean up the ribbon a bit)

But don’t forget that our Application Page is running from _layouts … it’s in a completely different place to our Web Part so this really isn’t enough for our page to work. In order to do anything else our Layouts page would need the following information:

  • The Page that the web part is on (URL)
  • Which Web Part to update on that page (Web Part ID)

The URL of the current page is easy enough using JavaScript (location.href) but the Web Part ID … this represented a new challenge.

How do you get the server-side Web Part ID through JavaScript?

This problem took the entire final hour of the day (Session 5) and took quite a bit of research and web searching. Eventually (after a few suggestions) we hit upon the answer:

Back in Part 2 we created a JavaScript file which was used to register our Contextual Tab. The JavaScript file that registers the Contextual Tab contains a reference to a “PageComponentId”.

getId: function ContextualTabWebPart_CustomPageComponent$getId() {
    return this._webPartPageComponentId;

Thes pecific instance of our Web Part had a “PageComponentID” of “WebPartWPQ2” and after some digging we found it in the Source of the page!

<div WebPartID=”866ef42d-6626-45e0-af9c-a00467ed2666″ WebPartID2=”1ad9529a-5e86-4e7c-9d4d-022a1fa6e6c0″ HasPers=”false” id=”WebPartWPQ2″ width=”100%” class=”ms-WPBody noindex ms-wpContentDivSpace” allowRemove=”false” allowDelete=”false” style=”” >

The attribute that REALLY stands out though is the WebPartID:


This is clearly a GUID value, referring to the server-side Web Part ID for that instance of the Web Part.
So .. how do we get this to our dialog.. well, good old trusty document.GetElementById() (we could have used JQuery, but I didn’t want to have to install the framework .. and don’t forget .. I only had 1 hour to get this working at SPRetreat!!)

Using this information, I could modify my JavaScript to retrieve these values, and pass them through to my Modal Dialog.

// get the Web Part DIV element
            var element = document.getElementById(this._webPartPageComponentId);
            // extract the Web Part ID (as a GUID object)
            var wpID = element.attributes[“WebPartId”];
            // pass through the URL and Web Part ID
            var options = {
                url: ‘/_layouts/SPR3/RCWP_SetFieldValue.aspx?wpID=’ + wpID.nodeValue + ‘&url=’ + location.href,
                title: ‘Set Field’,
                allowMaximize: false,
                showClose: true,
                width: 800,
                height: 600

Note – as the Web Part ID is of type HTML Attribute, we need to use the “NodeValue” property instead of toString();

So .. first off, in our Application Page we can use the URL to retrieve the fields from the page’s Content Type and populate our Drop Down List.

protected void Page_Load(object sender, EventArgs e)
            TargetUrl = Request.QueryString[“url”];
            // remove any query strings
            if (TargetUrl.IndexOf(“?”) != -1)
                TargetUrl = TargetUrl.Substring(0, TargetUrl.IndexOf(“?”));
            if (!Page.IsPostBack)
                SPFile file = this.Web.GetFile(TargetUrl);
                foreach (SPField field in file.Item.Fields)
                    if (!field.Hidden)
                        ListItem item = new ListItem(field.Title, field.StaticName);
            btnNike.Click += new EventHandler(btnNike_Click);

I did a bit of string manipulation on the URL to make sure we trim out any URL query strings, and then use that to retrieve an SPFile object.

We then just iterate through the SPListItem.Fields collection, adding any fields that are not hidden.

Note – we are using an ASP.Net ListItem object in the Drop Down List, so that we can use the Display Name in the drop-down, but store the Static Name as the value .. it’s the Static Name we need to save to our Web Part!

The next bit is under our Click event. We can now use the URL to get the SPLimitedWebPartManager for the page, and pass through the Web Part ID property, and it would retrieve the instance of my Web Part (allowing me to set the field value).

protected void btnNike_Click(object sender, EventArgs e)
           // get Web Part ID
           wpID = Request.QueryString[“wpID”];
           // retrieve the Web Part Panager for the URL
           SPFile file = this.Web.GetFile(TargetUrl);
           SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
           // get the safely-casted web part object
           RelatedContentWebPart.RelatedContentWebPart wp =
               wpm.WebParts[new Guid(wpID)] as RelatedContentWebPart.RelatedContentWebPart;
           if (wp != null)
               // set the web part property, and save settings
               wp.FieldName = ddlFields.SelectedValue;
           // close the modal dialog
           this.Context.Response.Write(“<script type=’text/javascript’>window.frameElement.commitPopup();</script>”);

So .. we should be done…

Build / Deploy / Test

So .. a long journey but worth it, five different 1 hour sessions and a great day at #SPRetreat .. but definitely worthwhile, and a new “Related Content Web Part” to boot!

A massive thanks to Andrew Woodward (21Apps) and Ben Robb (CScape) for organising the event, the venue and the food! (great food!!!)

Source Code

Sorry it took so long for me to get it all online, I was very busy then went on holiday. You can find all of the source code downloadable from my SkyDrive here:

RCWP Part 2 – Web Part with Ribbon Contextual-Tab

Also check out the other part of the series:

This follows on from Part 1, where we created a “Related Content Web Part” (RCWP) which would dynamically return search results based on the value of a field on the current page.

This post summarises the second-phase of that Web Part (which we started in session 4 of SPRetreat) to provide an easier method for the Content Editors to cherry-pick which field they wanted to use for the keyword search value. Seeing as me and my session 4 partner hadn’t done anything with Contextual Tabs before, we decided to give that a crack.

I’m not going to cover every single details of this. There are 2 fantastic articles:
Chris O’Brien (MVP) has a great 4-Part series titled “SharePoint 2010 Ribbon Customisation series” which is a must-read if you want to understand more about Ribbon development work.

There is also an excellent step-by-step guide on the Microsoft SharePoint Developer Documentation Blog called “How to create a Web Part with a contextual tab”.

In my example, I used the Microsoft blog’s example code, but there are plenty of good tutorials for this on the web. I’m not going to copy the same information in the blog article here, but the summarised core points are as follows:

  • Your Web Part must implement the Interface IWebPartPageComponentProvider(Microsoft.SharePoint.WebControls).
  • The Interface involves a WebPartContextualInfo property, which you use to register you “contextual” event
  • You will need a JS file to stored your “actions”
  • You will need XML configuration to register the definition of your “tab” and it’s controls.

So first off, we need to modify our web part to implement the Interface IWebPartPageComponentProvider:

public class RelatedContentWebPart : CoreResultsWebPart,
    // omitted for clarity

Now, before we implement the Interface we need to setup a few methods and properties.
First up is the XML schema for both the Tab Template and the Tab itself. It’s a lot of XML so I’m not going to post it here, but I basically copied the XML provided on the MS Blog post, so you should find it easy enough to go and fetch it from there or just use my Full Source Code (in Part 3).

A snippet of the first part is below;

private string contextualTab = @”
   <ContextualGroup Color=””Magenta””
     Title=””Related Content Web Part””
              Title=””Filtering Settings””
              Description=””This holds my custom commands!””
// remainder omitted for clarity

You can see that we have created a string called “contextualTab” that references a “ContextualGroup”. This has a colour, as well as a unique ID that we need to create. The Title will appear in the ribbon as the “contextual” group, which will span across multiple tabs (if you have multiple tabs in the same “contextual group” of course!).

Note – I have changed the title and description of my Tab and the Contextual Group, but everything else is the same as the MS Blog!

We also have a standard Ribbon “Tab” declaration, with an Id value which we will need later) as well as the Tab Title and Description.

Further down in the XML is a reference to the “Buttons” that we are going to have on our tab.
(Note – the code below is an exact copy of the “MS Blog Article” code .. we will be changing this later on!)

<Button     Id=””Ribbon.CustomTabExample.
    Description=””Show the Goodbye World text””
    LabelText=””Goodbye World!””

Make a note of where these button controls are, because we’re going to need to modify this in Part 3 of this post!

There is also another string created called “contextualTabTemplate” which you can use for the layout configuration.

private string contextualTabTemplate = @”
          <GroupTemplate Id=””Ribbon.Templates.CustomTemplateExample””>
              Title=””OneLargeTwoMedium”” LayoutTitle=””OneLargeTwoMedium””>
              <Section Alignment=””Top”” Type=””OneRow””>
                  <ControlRef DisplayMode=””Large”” TemplateAlias=””cust1″” />
// remainder omitted for clarity

So … now we have all of our XML defined we need to create a JavaScript file. The MS Blog article includes a JS file called “CustomContextualTabPageComponent.js” which deploys directly to the 14\Template\Layouts\ folder.
This contains a whole load of JavaScript for the Tab, Group and Button items in your XML file.

Important Note – The Command and Enable scripts use in your XML are in this JS file. If you start changing names you will need to manually keep these files in check.. they are XML and JS files so no compile errors or warnings! … except this one 😉

Probably the most important section in this file is that which handles the “Command” event for your buttons:

handleCommand: function ContextualTabWebPart_CustomPageComponent
    $handleCommand(commandId, properties, sequence)
    if (commandId ===
        ‘CustomContextualTab.HelloWorldCommand) {
            alert(‘Hello, world!’);
    if (commandId ===
        ‘CustomContextualTab.GoodbyeWorldCommand’) {
            alert(‘Good-bye, world!’);

Again, this code has been copied from the MS Blog, but keep a note of it .. we will be modifying this too in Part 3!

So .. we have our XML schema, and we have our JS file created, but we haven’t actually DONE anything with them yet.

So lets create a method to register our new Contextual Tab:

private void AddContextualTab()
            //Gets the current instance of the ribbon on the page.
            Microsoft.Web.CommandUI.Ribbon ribbon = SPRibbon.GetCurrent(this.Page);
            //Prepares an XmlDocument object used to load the ribbon extensions.
            XmlDocument ribbonExtensions = new XmlDocument();
            //Load the contextual tab XML and register the ribbon extension.
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, “Ribbon.ContextualTabs._children”);
            //Load the custom templates and register the ribbon extension.
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, “Ribbon.Templates._children”);

So .. this method is basically using the SPRibbon object to get a reference to the Ribbon on the current page. It is then loading in our XML schema to register a new contextual tab).
(Eventually we will end up calling this method from the PreRender() event).

Now we are going to need to register our JavaScript, and strangely enough we are going to do that with yet more JavaScript! (yes .. when you are working with the Ribbon JavaScript really is word of the day!)

public string DelayScript
            string webPartPageComponentId = SPRibbon.GetWebPartPageComponentId(this);
            return @”
            <script type=””text/javascript””>
            function _addCustomPageComponent()
                var _customPageComponent = new ContextualTabWebPart.CustomPageComponent(‘” + webPartPageComponentId + @”‘);
            function _registerCustomPageComponent()
                SP.SOD.registerSod(“”CustomContextualTabPageComponent.js””, “”\/_layouts\/CustomContextualTabPageComponent.js””);
                SP.SOD.executeFunc(“”CustomContextualTabPageComponent.js””, “”ContextualWebPart.CustomPageComponent””, _addCustomPageComponent);
            SP.SOD.executeOrDelayUntilScriptLoaded(_registerCustomPageComponent, “”sp.ribbon.js””);

The really important part of this is the first line:


This gets a unique reference for the instance of your Web Part, on the current page, in the context of the Ribbon. This is used to effectively identify your Web Part when someone clicks on it!
The other really important bit is the last line:

SP.SOD.executeOrDelayUntilScriptLoaded(_registerCustomPageComponent, “”sp.ribbon.js””);

This is the new “Script On Demand” (SOD) method which allows us to tell SharePoint not to try loading our JavaScript until the SP.Ribbon.JS has already been processed!
Once that has been done we need to implement our WebPartContextualInfo method:

public WebPartContextualInfo WebPartContextualInfo
                // create objects for the contextual web part tab
                WebPartContextualInfo info = new WebPartContextualInfo();
                WebPartRibbonContextualGroup contextualGroup = new WebPartRibbonContextualGroup();
                WebPartRibbonTab ribbonTab = new WebPartRibbonTab();
                //Create the contextual group object and initialize its values.
                contextualGroup.Id = “Ribbon.CustomContextualTabGroup”;
                contextualGroup.Command = “CustomContextualTab.EnableContextualGroup”;
                contextualGroup.VisibilityContext = “CustomContextualTab.CustomVisibilityContext”;
                //Create the tab object and initialize its values.
                ribbonTab.Id = “Ribbon.CustomTabExample”;
                ribbonTab.VisibilityContext = “CustomContextualTab.CustomVisibilityContext”;
                //Add the contextual group and tab to the WebPartContextualInfo.
                // fetch dynamic component info for the current page’s Ribbon control
                info.PageComponentId = SPRibbon.GetWebPartPageComponentId(this);
                return info;

Now lets take a quick look through some of this code first. The first thing you should notice is that there are 3 new classes provided in the OOB API specifically for providing contextual tabs (from Web Parts):

  • WebPartContextualInfo
  • WebPartRibbonContextualGroup
  • WebPartRibbonTab

These objects contains all of the core functionality that you will need to handle the interaction between selecting your Web Part in edit mode, and the Ribbon dynamically popping up your Tab when that happens.
The RibbonContextualGroup and RibbonTab objects then get given both an ID property and a VisibilityContext. These values refer to the same pointers in the XML schema definition for the Tab, Group and Controls that we are going to register (which we created earlier).
The final part of the puzzle is to add these to the Web Part’s load stack (in this case, the Pre-Render method):

protected override void OnPreRender(EventArgs e)
            ClientScriptManager clientScript = this.Page.ClientScript;
            clientScript.RegisterClientScriptBlock(this.GetType(), “ContextualTabWebPart”, this.DelayScript);

So, we are registering our contextual tab (using the AddContextualTab method we created earlier).
We then dynamically add a “lazy load” reference to our “DelayScript” string, which will register all of the JavaScript functions that we are using.

Build / Deploy / Test
There you have it … a contextual tab in edit mode!

Make sure you check back for:

  • RCWP Part 3 – Edit Web Part using a Ribbon modal dialog
  • (Full source code for the solution will be published in Part 3)

    RCWP Part 1 – SPRetreat and the Related Content Web Part

    I’m sat on the train after a great day of SPRetreat (followed by SharePint of course!), superbly organised by Andrew Woodward (21Apps) and Ben Robb (CScape). It was a really good day of innovative ideas, problem solving, chewing the fat (and the occasional dirty joke… you know who you are!).

    The core challenge thrown down for the day involved trying to provide cross-site (collection) “related information”, effectively a “cross-pollination” function, using SharePoint 2010. There were some great ideas and a lot of top effort into involving the Managed Metadata Service, Custom Search API work and some cracking Scrum / Agile design processes.

    We had 5 sessions of 1 hour each, and my efforts for the day mostly revolved around delivering a “Related Content Web Part”, which could use Search to show other content from any data source which is in some way related to the information on the current page.

    In this post I’m going to walk through how my efforts of the day culminated in the “Related Content Web Part” but ended up being a generic “Dynamic Field Driven Search” web part, basically allowing a set of search results to be displayed based on the value of a field that is stored in the publishing page (i.e. content type) that contains the web part (which derived from the Search CoreResultsWebPart).

    In the final sessions we though about how to improve this, and ended up building a custom contextual ribbon interface to surface SP Modal Dialogs to allow easy updating of core web part properties.
    Core Functionality

    The functionality is really split into 3 major sections:

    (Full source code for the solution will be published in Part 3)

    RCWP Part 1 – Extending the Core Results Web Part
    This is one of the nicest new “features” of SharePoint 2010. They have stopped sealing all of the Web Parts (and Web Part Connections)that are used for the results pages in SharePoint Search solutions. This means it is now much easier for you to extend and add-value to these web parts without having to throw out all of the OOB functionality.
    The reason for using the CoreResultsWebPart was simple;

    • Using search is fast, efficient, cross farm and highly configurable.
    • The core results web part using XSLT for rendering, so easy to design the output.
    • Leveraging an OOB web part means we get loads of added functionality for free! (like specifying which scope we want to use).

    In this solution, we extended the CoreResultsWebPart to create our own Web Part. Simple create a new Visual Studio 2010 “Web Part” item and set it to inherit from “CoreResultsWebPart” (you will need to add a reference to Microsoft.Office.Server.Search.dll).

    public class RelatedContentWebPart : CoreResultsWebPart

    In terms of functionality we need to do 1 thing:

    Override the Query programmatically, based on the metadata of the current page.

    This involved a few steps. First off, we need to identify which field we want to be “targeting”. For this we created a simple string field, exposed as a Web Part Property.

    private string fieldName = “Title”;
    /// The field on the current page we want to use for filtering
    [WebDisplayName(“Field Name”)]
    [SPWebCategoryName(“Filter SPR”)]
    [Description(“Which field on the current page do you want to use for filtering?”)]
    public string FieldName
    { get { return fieldName; } set { fieldName = value; } }

    Then we needed to override the query itself. This is simply done by setting the “FixedQuery” property of the CoreResultsWebPart. The trick here is you need to set this in the “OnInit” event, otherwise it won’t take effect (if you try to place it in OnLoad, CreateChildControls or any other later method then it won’t have any effect!).

    protected override void OnInit(EventArgs e)
        this.FixedQuery = “keyword string value”;

    Finally, we need to make sure we are pulling out the field value of the current list item, based on our custom field. For this we used a simple set of SPContext combined with some defensive programming to make sure we don’t get any NullReferenceException errors. So change the “OnInit” event to the following:

    protected override void OnInit(EventArgs e)
        if (!string.IsNullOrEmpty(fieldName))
                this.FixedQuery =

    After that … Build / Deploy and the web part was working!

    The code could obviously be re-factored a little bit, but on the whole it’s all working 🙂
    Make sure you check back for:

  • RCWP Part 2 – Web Part with Ribbon Contextual-Tab
  • RCWP Part 3 – Edit Web Part using a Ribbon modal dialog
  • (Full source code for the solution will be published in Part 3)

    SP 2010 Websites and JavaScript “on demand” bug

    We are currently working on building the new Content and Code website on SharePoint 2010. This is a “brochure-ware” anonymous publishing site, and as such it is fairly lightweight (with most of the normal “heavy” JS files for things like the SP Ribbon, dialogs framework and the like not required).


    You can imagine my surprise when our landing page was showing up as over 650KB in size! On further inspection, the vast majority of this was OOB JavaScript files (including the Ribbon, dialog and core JS files!).


    I thought we’d made a mistake so I checked an OOB Publishing Portal and even the public “” website (both had the same problem) so it appears this is a more fundamental problem! Importantly, ALL of these tests are as an anonymous user!


    Lazy Load vs On Demand

    The first thing to mention is that these files are on “lazy load” (i.e. they load AFTER the UI has been rendered). So end users don’t really notice .. the page is displayed fairly quickly, and the remaining JS files download in the background.


    But lets be clear, this is NOT “on demand” JS. Files are clearly being loaded that should NEVER be required by anonymous users (like the ribbon??)

    The “On Demand” was one of the major infrastructure improvements to promote fast and efficient web-based systems, and for custom development works a charm (my own visual web part with on-demand JS worked perfectly .. the custom JS file didn’t get downloaded until I called a specific JS function).



    The second thing to mention is that it appears these files are only downloaded once. Doing repeated page requests (or even “Ctrl-F5” full load requests) do not bring back these files unless you do a full clear of your browser cache (or try using a different browser) but it does mean that the “first hit” page size is rather large to say the least.


    So how many files are we talking about?


    I decided to test this on a public facing SharePoint 2010 Website, and the easiest one that sprang to mind was (a newly launched Microsoft site powered by SharePoint 2010 specifically for the launch).


    I was using Fiddler for the session information (as I could use it for multiple browsers, and knew it was independent to the actual page-source).

    I found that, on the first page hit (subsequent pages do not load them) the following JavaScript references were being downloaded (size in Bytes shown in brackets):

    • core.js (237,096)
    • sp.core.js (12,349)
    • cui.js (351,361)
    • sp.ui.dialog.js (34,243)
    • sp.runtime.js (68,784)
    • sp.js (389,372)
    • inplview.js (38,836)

    You can see the actual page statistics below, where the 9 JavaScript references represent 1,362,477 Bytes of data! (that’s over 1MB of JavaScript!)


      Is there a solution?


    Well, I haven’t looked too deeply into a solution yet (still peeling back layers looking for what is causing the “on demand” to load on first hit).

    One solution is not to use the <SharePoint:ScriptLink> control, and manually refer to whichever JS files you need in your Master Page (using Edit Mode Panels and Security Trimmed Controls to make sure the appropriate JS is available for editing experience and the like).


    This however is a complicated approach and requires quite a deep understanding of the JS files, what they do and when they are required (not for the faint hearted).


    I would certainly be very keen to hear about your run in with this particular issue. Do you experience this issue on your environments? Have you managed to get around it yet?


    Meanwhile I’ll continue my on-going love-hate relationship with SharePoint and try to work out how to stop my website having a 1MB page payload.