Adding Pages to SharePoint Site Programatically

To add pages to a Publishing site you first need to get an instance of a PublishingWeb object. Then, you need to get a content type (this wasn’t so obvious because the SPContentTypeID object isn’t documented in the WSS v3 SDK… as of the latest available SDK at least [Beta 2 Tech Refresh]), a page layout, and finally create the page.

Here’s the sample code… have at it! It only fills the root site in the site collection with pages, but it should be pretty clear to any SharePoint developer how to add pages to subsites as well. It assumes the site collection was created using the Publishing Portal site template (from MOSS 2007 B2TR) because it expects both the Article Page content type and ArticleLeft.aspx page layout exist.

   1:  public void FillPublishingWebWithPages (string publishingSiteCollection, int pagesToCreate) {
   2:    SPSite siteCollection = null;
   3:    SPWeb site = null;
   4:    PublishingSite publishingSite = null;
   5:    PublishingWeb publishingWeb = null;
   6:   
   7:    try {
   8:      // get the PublishingWeb
   9:      siteCollection = new SPSite(publishingSiteCollection);
  10:      site = siteCollection.RootWeb();
  11:      publishingSite = new PublishingSite(siteCollection);
  12:      publishingWeb = PublishingWeb.GetPublishingWeb(site);
  13:   
  14:      // Article Page content type
  15:      SPContentTypeId articleContentTypeID = new SPContentTypeId("0x010100C568DB52D9D0A1
4D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D");
  16:      
  17:      // get the ArticleLeft.aspx Page Layout 
  18:      PageLayout[] layouts = publishingWeb.GetAvailablePageLayouts(articleContentTypeID);
  19:      PageLayout articlePageLayout = layouts[1];
  20:      
  21:      // create a temp name...
  22:      string pageName = DateTime.Now.ToString("yyyyMMdd-HHmmss");
  23:      
  24:      // create the specified number of pages
  25:      for (int i = 0; i < pagesToCreate; i++) {
  26:        PublishingPage newPage = publishingWeb.GetPublishingPages().Add(
string.Format("{0}_Gend_Page_{1}.aspx", pageName, i), articlePageLayout);
  27:        newPage.Update();
  28:      }
  29:    } catch (Exception ex) {
  30:      throw new Exception(ex);
  31:    } finally {
  32:      // properly dispose of the resources
  33:      site.Dispose();
  34:      siteCollection.RootWeb.Dispose();
  35:      siteCollection.Dispose();
  36:    }
  37:  }

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s