Pages

Monday, May 23, 2011

Adding PublishingPageImage programmatically – SharePoint Publishing Pages

Here is simple console application, which adds /sets the Image for SharePoint Publishing Page
Well, some basics before to dive in to the code,
When you create any Publishing Page in SharePoint then by default it gets created from Publishing Page content type, and so by default it has some fields to store the associated metadata
If you want to see names of all fields associated with default publishing page content type then this is how simply you can do
Go to 12 hive feature folder, search feature with name PublishingResources, open file with name PublishingColumns.xml (you can find more files in this feature such as PublishingContentTypes.xml , If you are interested to know then you can have look at these files too)
class Program
{
 static void Main(string[] args)
 {
  try
  {
    using (SPSite site = new SPSite("http://yoursite"))
    {
      using (SPWeb web = site.RootWeb)
      {
        if (PublishingWeb.IsPublishingWeb(web))
        {
          PublishingWeb _pweb = PublishingWeb.GetPublishingWeb(web);
          if (_pweb != null)
          {
            if (_pweb.DefaultPage.Level != SPFileLevel.Checkout)
            {
             if (_pweb.DefaultPage.Item[FieldId.PublishingPageImage] as  ImageFieldValue == null)
             {
               _pweb.DefaultPage.CheckOut();
               ImageFieldValue _field = new ImageFieldValue();
               _field.ImageUrl = "/SiteCollectionImages/home.gif";

                                          _pweb.DefaultPage.Item[FieldId.PublishingPageImage] = _field;
            _pweb.DefaultPage.Item.Update();
            _pweb.DefaultPage.CheckIn("Added Image");
            if (_pweb.PagesList.EnableMinorVersions)
            {
              _pweb.DefaultPage.Publish("Published");
             }
           if (_pweb.PagesList.EnableModeration)
           {
             _pweb.DefaultPage.Approve("Approved!!");
           }

              Console.WriteLine("Image Added");
          }
                                   
         }
        }
       }
      }
     }
    }
    catch (Exception ex)
    {
      Console.WriteLine("Error :" + ex.Message);
    }

       Console.ReadLine();
    }
  }

No comments:

Post a Comment