Andrew Connell [MVP MOSS]
1402 Posts |  39 Articles |  3659 Comments
.NET  |  MCMS  |  SharePoint  |  Office System
SharePoint Quick Links
Article Categories
Archives
Post Categories


Add to Technorati Favorites

This code has been tested with MOSS 2007 RTM (it was originally written and tested with MOSS 2007 B2TR). Thanks Aaron!

When I was adding unit tests to my WCM Custom Commands for STSADM.EXE suite, I needed to have some pages were automatically added to a Publishing site to test the PublishAllItems custom command. I figured this may be something other developers need to do so I figured I'd throw this sample code in a post for my readers.

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:  }
 
 
Technorati: ,
posted on Wednesday, November 15, 2006 1:37 AM

Feedback

 re: Programmatically adding pages to a MOSS Publishing site 2/15/2007 3:11 PM Andy
Gravatar Thanks - this was exactly what I was looking for! I tried several ways to add a page and your solution was the best fit.

one note about line 10 - site = siteCollection.RootWeb(); should be changed to site = siteCollection.RootWeb;

# re: Programmatically adding pages to a MOSS Publishing site 2/15/2007 10:46 PM AC [MVP MOSS]
Gravatar Andy-
Correct... RootWeb is a property, not a method. Good catch!

# re: Programmatically adding pages to a MOSS Publishing site 4/12/2007 1:48 PM Thomas Goddard
Gravatar Any idea how to do this with a Wiki page? I need to fill in a couple fields in the wiki page "wiki content and tags", and then create the page. I don't see this documented anywhere and CreateWebPage.aspx uses the FieldIterator so there is no way of knowing which fields do what. CreateWebPage.aspx is using Microsoft.SharePoint.ApplicationPages.CreateWebPage, which by the way is stored in the _app_bin (INSANE!) and now I am just trying to figure out how to do what that class is doing bu thtere are so many dependencies it's crazy.

 re: Programmatically adding pages to a MOSS Publishing site 5/15/2007 1:43 AM motmot
Great code guys, but where do i put this code? Is this a dll that i should deploy on the sharepoint bin? Im new to MOSS programming and i was wondering if you guys could help me out. Thanks!

# re: Programmatically adding pages to a MOSS Publishing site 5/15/2007 6:14 PM AC [MVP MOSS]
Gravatar Motmot-
You can run this from a console app or any other compiled assembly.

 re: Programmatically adding pages to a MOSS Publishing site 5/24/2007 10:54 AM Yiannis
Gravatar Great code,
do you have any ideas how can i add the page to a sub-folder
instead of the root folder?

thanks in advance

 re: Programmatically adding pages to a MOSS Publishing site 7/27/2007 4:57 PM Kyle
Gravatar I inherited some code doing just this (he probably got it here), and need to redirect to the created page afterwards. Thats the easy part. But it would be nice if the page could automatically be placed in edit mode upon redirection. Any idea how to do this?

Thanks,

Kyle

 re: Programmatically adding pages to a MOSS Publishing site 8/28/2007 4:06 AM Balle
Gravatar - Kyle -

You can redirect users to the new page, and also be placed in edit mode by passing &quot;*.aspx?ControlMode=Edit&quot; in the URL.

For this to work properly, the Page (File) must be checked out to the current user.

I use this approach in my solution, and it's working perfectly...

Balle

 re: Programmatically adding pages to a MOSS Publishing site 9/6/2007 12:40 AM Jaya Borra
Gravatar Is there any way of setting permissions to the publishing page programatically?
That means giving contributor permissions to an user on the desired page programatically

# re: Programmatically adding pages to a MOSS Publishing site 9/6/2007 1:22 AM AC [MVP MOSS]
Gravatar Jaya-
You bet... you'd use an event receiver to implement this. Specifically, look at the SPRoleDefinition and SPRoleAssignment classes.

 How to add page content? 10/10/2007 5:39 AM aung
Gravatar How can I add Page Content and image to the newly created page? i can't find the way. :-(

# re: Programmatically adding pages to a MOSS Publishing site 10/10/2007 8:40 AM AC [MVP MOSS]
Gravatar Aung-
They are just fields within the new list item. In the code above, the newPage object is of type PublishingPage. If you get the underlying SPListItem, you can add data such like this: newPage.ListItem["PublishingContent"] = "some content";

 re: Programmatically adding pages to a MOSS Publishing site 11/8/2007 8:29 AM piyush
Gravatar Great site. Got me started when I was new to MOSS. But how do you re-create a page? Is there a setting to recreate if the page already exists or is there a way to quickly find a page and delete it so that the .Add() doesn't fail. Ran into this problem when I am trying to periodically update some pages.

 re: Programmatically adding pages to a MOSS Publishing site 11/20/2007 4:58 AM chris
Gravatar hi andrew,

any idea how we can achieve this on sites not using the publishing feature?
I need to do something like this in mysite? Is it possible?

# re: Programmatically adding pages to a MOSS Publishing site 11/20/2007 2:14 PM AC [MVP MOSS]
Gravatar Chris-
As in how to create new items in a SharePoint list? Just do something like:

SPListItem newItem = someList.Items.Add();
newItem.Title = "Some title";
newItem.Update();

If you want to create new pages, you'll need to have a document library to create them and then create new items in the doc lib. There is plenty of code out there demonstrating this. Just run a search for creating new files in document libraries.

 re: Programmatically adding pages to a MOSS Publishing site 1/3/2008 8:28 AM Rafa
Gravatar Hi Andrew,
great article! Very useful.
Just one question... is it possible to add a new publishing page to a site using web services (from remote access) ?
Thanks in advance.

 re: Programmatically adding pages to a MOSS Publishing site 2/13/2008 8:22 AM Ashok
Gravatar hai

 re: Programmatically adding pages to a MOSS Publishing site 3/4/2008 5:57 PM MK
Gravatar Has anyone tried this with variations enabled? Seems like the variation timer job doesn't seem to catch up with all of the pages i'm creating.



 re: Programmatically adding pages to a MOSS Publishing site 4/22/2008 5:00 AM Vikram
Gravatar Hi Andrew,

Thanks for this great article.

I was able to add some content to the Page created with

newPage.ListItem["Page Content"] = "some content";

But couldnt figure out how to add an Image to the List Item
"Page Image"I tried using

newPage.ListItem["Page Image"]= "MyImages/ipl.jpg";

which dint work. Please help.

# re: Programmatically adding pages to a MOSS Publishing site 4/22/2008 9:01 AM AC [MVP MOSS]
Gravatar Vikram-
The URL field types store a comma delimited value to store the name of the link and the nagivation target. You'll need to add two values, one is the text, one is the text URL where the image resides.

 re: Programmatically adding pages to a MOSS Publishing site 4/24/2008 4:31 AM Vikram
Gravatar I was able to add an image to the "Page Image" List Item of the article page by using

newPage.ListItem["Page Image"] = "<img alt=\"\" border=\"0\" src=\"/MyImages/ipl.jpg\" style=\"BORDER: 0px solid; \">";


It accepted a HtmlTag Value.

 re: Programmatically adding pages to a MOSS Publishing site 5/8/2008 1:00 PM John Mc
Gravatar Wow, this article & it's comments were EXACTLY what I needed. Thank you so much, and keep up the good work!

 re: Programmatically adding pages to a MOSS Publishing site 5/30/2008 2:03 AM Sudhakar
Gravatar We are attempting to create page based on our custom layouts through code ( same APIs as above). (code would be run as seperate exe)

However our custom page layouts have webpartzones+webparts embedded. This being the case, code fails in the step publishingpage.add -> error beign 'No parameterless constructor defined' ( raised by SPWebPartManager).
Please help.


 re: Programmatically adding pages to a MOSS Publishing site 9/18/2008 9:54 AM Sidhu
Gravatar Hi,

I want to add new .aspx pages based on SNO in Sharepoint Pages Library.Please help.....

 re: Programmatically adding pages to a MOSS Publishing site 9/19/2008 3:19 AM vijai
Gravatar Hi,

I had a created a webpart using the above code also imported the webpart in collaboration portal, but pages are not been created, I checked in pages folder there is only default.aspx, non of the pages created.

Can you please help me

-vijai

 re: Programmatically adding pages to a MOSS Publishing site 11/10/2008 12:14 PM MOSSBUDDY
Hi Andrew,
Is there anyway to create more than one PAGES library in a Publishing Portal, I want to create 2 Pages library one for Anonymous users and other for Authenticated users. But unfortunately thru MOSS UI i dont see an option to create another PAGES library and bydefault all pages are created in the PAGES library. Is there any workaround or anything that I am missing.

thanks
MB

# re: Programmatically adding pages to a MOSS Publishing site 11/10/2008 5:42 PM AC [MVP MOSS]
Gravatar MOSSBUDDY-
Nope... only one per Publishing site.

 re: Programmatically adding pages to a MOSS Publishing site 11/10/2008 6:29 PM MOSSBUDDY
Thank you Andrew, do you have any suggestion/advice on creating pages (1 for authenticated users and other for anonymous users)?
Basically there are 4 pages for Anonymous users and 4 for authenticated users, if we place all 8 in Pages library and enable anonymous access on Pages library then the ANONY users will be able to access the AUTHENTICATED 4 pages, which we would like to avoid, any suggestion?
Thanks

# re: Programmatically adding pages to a MOSS Publishing site 11/10/2008 6:34 PM AC [MVP MOSS]
Gravatar MOSSBUDDY-
Item level security... break permission inheritance on the items you want to secured/anonymous and set it individually OR create two separate sites, one for anon and one for auth users.

 re: Programmatically adding pages to a MOSS Publishing site 11/10/2008 6:44 PM MOSSBUDDY
Thank you Andrew, you are sincerely a very good, great and helping person. Thank you once again.

 re: Programmatically adding pages to a MOSS Publishing site 11/10/2008 10:05 PM MOSSBUDDY
Hi Andrew,
I checked for Item level security and unfortunately there is no way to set ANONYMOUS access at Page (Item) level and as you suggested for 2 sites (1 for anonymous users and 1 for authenticated users) will not work as the URLs change. Is there any other way out.

Thanks


# re: Programmatically adding pages to a MOSS Publishing site 11/11/2008 3:55 AM AC [MVP MOSS]
Gravatar MOSSBUDDY-
Set the libarary to anon then secure the desired items. BTW, you should use the MSDN Forums for support questions unless you have a comment about a specific post.

 re: Programmatically adding pages to a MOSS Publishing site 11/12/2008 5:30 AM Piotr
Gravatar Hi,
I am getting a permission issuue on line 18.
The login popup box shows up, and I need to create a page as anonymous user. Help please!

# re: Programmatically adding pages to a MOSS Publishing site 11/12/2008 7:44 AM AC [MVP MOSS]
Gravatar Piotr-
OOTB anonymous users won't work. It's running under the identity of the logged in user. So this means you don't have permissions to add the content. Just grant contributor rights to the person who's running the code.

Post Feedback

Title:
Name:
Email:
(email will not be displayed)
Url:
Comments: 
Please add 5 and 3 and type the answer here:    
All Comments Are Filtered & Moderated
Unfortunately comment spammers are just too effecient and are constantly dirtying up blogs with irrelivant and unwanted comments trying to improve their standing on search engines. All comments on this blog are moderated. I do not censor comments, but I don't approve comments with vulger language or those soliciting products. Most of the time comments are approved within a few hours of being submitted with the only exception when I'm traveling.

Why are you asking for my email address?
The only reason I'm asking for your email address, which isn't required to submit a comment, is to provide a gravatar if you've created an account for yourself and associated your email address with a small image. If you have a gravatar created for the email address you submit, it will appear next to your comment. Otherwise nothing will appear.

What is a gravatar?
A gravatar is a "globally recognized avatar." You can get more information about gravatars, as well as create your own for free, at www.gravatar.com. You can also view my gravatar here.


Copyright © 2003 - 2008 Andrew Connell
Creative Commons License 
This work is licensed under a Creative Commons License
Site design by Heather Solomon.

 
 
MOSS WCM Training
Looking for MOSS 2007 WCM developer training? Look no further! I teach my 4-day hands-on and 5-day online WCM classes for developers I offer through the Ted Pattison Group.

Get more information on the WCM courses!


Upcoming Classes
 Hands-on WCM:
 » Tampa, FL
   Jan 12-15, 2009
 Online WCM:
 » Dec 8-12, 2008


» Register today!

JAX Office Geeks
Jacksonville Office Geeks (JOG)
JOG is a special interest group in Jacksonville, FL dedicated to bringing the local SharePoint commnity together to share tips, tricks, ideas and best practices for developing solutions on the SharePoint platform.

Next meeting details...
When:
Thur. Nov 20th, 2008
  6-8p EDT
Topic:
Creating & Debugging Custom Timer Jobs in WSS

Speaker:
Andrew Connell, MVP MOSS

RSVP Today!


» Subscribe to the JOG newsletter