Programmatically creating a MOSS publishing page

mosssharepoint

I'm getting an error when creating a MOSS publishing page (this is a completely clean MOSS install, no site built into it yet). I'm using code which I've found on plenty of blogs, eg:

var pubWeb = PublishingWeb.GetPublishingWeb(Site.RootWeb);
SPContentTypeId ctId = new SPContentTypeId(contentTypeId);
var layouts = pubWeb.GetAvailablePageLayouts(ctId);
var layout = layouts[0];

var url = pageTitle.EndsWith(".aspx") ? pageTitle : pageTitle + ".aspx";
var newPage = pubWeb.GetPublishingPages().Add(url, layout);

But when I do the pubWeb.GetPublishingPages().Add method call I get the following error:

FormatException – Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

I've checked the following:

  • ContentTypeId is valid
  • layout has a value
  • pubWeb.GetPublishingPages().Count == 1

I can't seem to find anything useful via Google nor can I find anything in Reflector which could help.

Best Answer

I found out what the problem was, the ContentType I was using was corrupt. Because of another problem I'm having deploying ContentTypes (see this question) I'm programatically creating the ContentType, but deploying the PageLayout with CAML. This resulted in the AssociatedContentType being incorrect, so when I created the page using it MOSS was unable to determine what ContentType to use and fell over.