Wednesday, May 14, 2008

Accessing SharePoint Publishing Pages With The Object Model

Here's a quick and dirty code sample that "visits" each page in every publishing site within a SharePoint site collection.

In this case, "visiting" consists of writing the check-out and approval status of each page to the console and (if necessary) ensuring that the page is checked-in and approved.

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace MyUtilities
{
class Program
{
static void Main(string[] args)
{
const string indent = " ";

using (SPSite site = new SPSite("http://SomeSite"))
{
SPWebCollection webs = site.AllWebs;

foreach (SPWeb web in webs)
{
// only look at publishing sites
if (!PublishingWeb.IsPublishingWeb(web))
{
continue;
}

PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);

Console.WriteLine("Site: {0}", pubWeb.Title);

PublishingPageCollection pages = pubWeb.GetPublishingPages();
foreach (PublishingPage page in pages)
{
SPModerationInformation mi = page.ListItem.ModerationInformation;

Console.WriteLine("{0}{1}: Check-out status-{2} Approval status-{3}.",
indent, page.Title,
page.ListItem.File.CheckOutStatus, mi.Status);

try
{
if (page.ListItem.File.CheckOutStatus != SPFile.SPCheckOutStatus.None)
{
page.CheckIn("Automatically checked-in");
Console.WriteLine("{0}*** Checked-in", indent);
}
}
catch (Exception e)
{
Console.WriteLine("{0}Unable to check-in page {1}. Exception: {2}",
indent, page.Title, e.Message);
}

try
{
if (mi.Status != SPModerationStatusType.Approved)
{
page.ListItem.File.Approve("Automatically approved.");
Console.WriteLine("{0}*** Approved", indent);
}
}
catch (Exception e)
{
Console.WriteLine("{0}Unable to approve page {1}. Exception: {2}",
indent, page.Title, e.Message);
}
}
}
}
}
}
}


No comments: