Archive for the ‘Wiki’ Category

Adding a Webpart to home.aspx during Site creating in Enterprise Wiki

September 8, 2010

Consider following scenario:

Create a custom site template based on Enterprise Wiki (Publishing Site) and add a web part to the home page during site creating.

The creating of the template is not tricky and you can find the description here.  The tricky part is actually adding the web part to the homepage.

So here is how you can do it:

Delete the module that creates the home.aspx from the onet.xml. and create it manually in code behind (I used a feature receiver on a feature that is activated when the site is created. The method that adds the homepage can look like this.

public static void AddHomePageToDocumentLibrary(SPWeb web, string pageContent)
{
        var pubWeb = PublishingWeb.GetPublishingWeb(web);
        var pageLayout = pubWeb.GetAvailablePageLayouts()[0];
        PublishingPage newPage = pubWeb.GetPublishingPages().Add("home.aspx", pageLayout);
        newPage.ListItem[FieldId.PublishingPageContent] = pageContent;
        newPage.ListItem.Update();
        newPage.Update();
}

The page content should contain following div:

<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false'><div class='ms-rtestate-read d127f8fd-2a2e-4495-9e0f-d32d5ca2e5c7' id='div_d127f8fd-2a2e-4495-9e0f-d32d5ca2e5c7'></div><div style='display:none' id='vid_d127f8fd-2a2e-4495-9e0f-d32d5ca2e5c7'></div></div>

This div is by run time replaced with an actual webpart. The guid d127f8fd-2a2e-4495-9e0f-d32d5ca2e5c7 is important as it identifies the webpart that should be added to the page.

Finally we have to add the webpart to the webpart zone.


public static void AddWebPartToHomePage(System.Web.UI.WebControls.WebParts.WebPart webPart, SPWeb web, Guid webpartId)
        {
            using (SPLimitedWebPartManager mgr = web.GetLimitedWebPartManager("seiten/home.aspx", PersonalizationScope.Shared))
            {
                string storageKeyId = StorageKeyToID(webpartId);
                webPart.ID = storageKeyId;
                mgr.AddWebPart(webPart, "wpz", 0);
            }
        }

private static string StorageKeyToID(Guid storageKey)
        {
            if (!(Guid.Empty == storageKey))
            {
                return ("g_" + storageKey.ToString().Replace('-', '_'));
            }
            return string.Empty;
        }

The webpart is the webpart we want to add, web is the web that we create and the guid is the guid that identifies the webpart. In our case it is d127f8fd-2a2e-4495-9e0f-d32d5ca2e5c7. The “wpz” zone is the hidden webpart zone that SharePoint 2010 uses to store inline webparts.

I tried to create these webparts in onet.xml, but it did not work. The webparts were simply not displayed, though all attributes were filled.

References

http://donalconlon.wordpress.com/2010/05/04/sp2010-creating-a-wiki-page-using-the-om/

Advertisement