Programmatically create pages – and Add Web Parts

I had an interesting problem recently with a Site Definition. I was trying to create a publishing page, which would not create as the correct content type. I still haven’t got to the bottom of why.

However, time was limited, and we were going to have to create a feature receiver to staple to our site definition anyway, so I had a look at creating a publishing page programmatically.

We needed a feature receiver as the customer wanted the home page of their site to have a ‘Search Box’ which would ‘Search this site’, but go to a custom results page in a Search Center. My plan was to use a Search Box Web part, configured to go to a custom results page, and to append the query term:

site: [url to site]

e.g. site:http://sharepoint/finance/

Naturally, you don’t know the URL of the site until the site has been created – so this web part would have to be created programmatically.I won’t go through all my code; that would be a little long winded. Looking at the cool bits, though:

web is the SPWeb for the new site

contenttypeID is the ‘0x01010…’ string ID of my content type

pageLayoutName is the name of the page layout I want to use (‘myLayout.aspx’)

title is the title for the page!

// **********************
// * Create the Page
// **********************
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);
SPContentTypeId cTypeId = new SPContentTypeId(contenttypeID);
PageLayout[] layouts = pWeb.GetAvailablePageLayouts(cTypeId);
PageLayout layout = layouts[1];
foreach (PageLayout p in layouts)
if (p.Name == pageLayoutName)
layout = p;
PublishingPage newPage = pWeb.GetPublishingPages().Add(fileName, layout);
newPage.Title = title;

First, we get a PublishingWeb object, and use that to get the available page layouts for the site. I loop over the available layouts looking for the one I want to use, and then add a new page. It works nicely.

The second part of my code was creating a Searchbox WebPart on my page:

// **********************
// * Add the Search Box
// **********************
SPFile file = web.GetFile(listName + "/" + fileName);
if (!file.Exists)
throw new SPException(string.Format("File '{0}' does not exist", file.ServerRelativeUrl));
if (list.ForceCheckout && (file.CheckOutStatus == SPFile.SPCheckOutStatus.None))
SPLimitedWebPartManager partManager = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
SearchBoxEx part = new SearchBoxEx();
part.Title = "Auto Site Search";
part.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;
part.QueryPromptString = "Search This Site";
part.AppendToQuery = true;
part.AppQueryTerms = "site:" + web.Url;

part.DropDownMode = DropDownModes.HideDD_NoScope;
part.ShowAdvancedSearch = false;
part.SearchResultPageURL = customResultsPageUrl;
partManager.AddWebPart(part, zone, 1);
if (list.ForceCheckout)
file.CheckIn("Auto Search Box Added");
file.Publish("Web Part Added");
if (list.EnableModeration)
file.Approve("Auto Approved");

This code gets the file for the page, and then gets the web part manager for it. I create a new SearchBox, and set things like the title, chrome, appearance and so on. The two lines in bold are what appends the ‘site:[url]’ term to our query which is submitted to the custom results page. This is what simulates being a ‘contextual’.

All in all, not the tidiest, but it works.

Programmatically create pages – and Add Web Parts

5 thoughts on “Programmatically create pages – and Add Web Parts

  1. anis says:

    How to display the site owners name just above the search box in the site master page. I have a requirement to display the site owners name in the master page of each site and their respective sub sites.
    Kindly provide a solution

  2. Boyana says:

    How do you find the ID of the zone of the page where you want to add the webpart?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.