Thursday, August 28, 2008

Fixing page layout URLs after importing a publishing site in SharePoint

Sometimes when you importing a publishing site in sharepoint, you may failing to copy some pages. If you looked at the page in the pages library the name of the layout was correct, but the link pointed to a different site(URL was pointing to the site from which I originally imported the site, but only some pages were broken). This problem may generate error "Value does not fall within the expected range".

Fixing the PageLayout URLs
A console application which looked at each of the pages and modified the link to the layout.
Code To do this action is:

private static void FixPages(SPWeb oWeb)
{
try
{
if (!PublishingWeb.IsPublishingWeb(oWeb)) return;
PublishingWeb pw = PublishingWeb.GetPublishingWeb(oWeb);
SPListItemCollection oList = pw.PagesList.Items;
string sSiteUrl = oWeb.Site.Url;
foreach (SPListItem oPageItem in oList)
{
string s = (string)oPageItem[FieldId.PageLayout];
if (!s.StartsWith(sSiteUrl))
{

Console.WriteLine("Fixing " + oPageItem.Title + " (" + oPageItem.Url + ")");
oPageItem[FieldId.PageLayout] = sSiteUrl + s.Substring(s.IndexOf("/", 9));
oPageItem.SystemUpdate();
}
}
foreach (SPWeb oSubWeb in oWeb.Webs)
{
Console.WriteLine("Processing " + oSubWeb.Title + "...");
FixPages(oSubWeb);
oSubWeb.Dispose();

}
}
catch (Exception ex)
{
Console.WriteLine("Layout fix failed at site: " + oWeb.Title);

Console.WriteLine(ex);
}
}

Running this application against the development site found a number of pages where the layout was broken and fixed up the link. Running it for a second time confirmed all the layout URLs were fixed.

No comments: