Adding PublishingPageImage Programmatically-SharePoint Publishing Pages


Here is a simple console application, which adds / sets the Image for a SharePoint Publishing Page.

Well, first some basics before diving into the code.

When you create any Publishing Page in SharePoint then by default it is created from the Publishing Page content type, and so by default it has some fields to store the associated metadata.

If you want to see the names of all fields associated with default publishing page content type then this is how simply you can do it.

Go to 12 hive feature folder, search feature with name PublishingResources, open the 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 a look at these files too).

We can always set the Publishing Page Image using SharePoint default UI (when we edit the page and edit the metadata), but what If we want to achieve this using programatically?

I have tried to do this and here is the Console Application I created.

Please Note that you have to add a SharePoint specific dll to the project so that your code compiles successfully.

 

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();

    }

  }