Adding PublishingPageImage programmatically – SharePoint Publishing Pages

n

nHere is simple console application, which adds /sets the Image for SharePoint Publishing Page

n

nWell, some basics before to dive in to the code,

n

nWhen 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

n

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

n

nGo 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)

n

nclass Program

n

n{

n

n static void Main(string[] args)

n

n {

n

n  try

n

n  {

n

n    using (SPSite site = new SPSite(“http://yoursite”))

n

n    {

n

n      using (SPWeb web = site.RootWeb)

n

n      {

n

n        if (PublishingWeb.IsPublishingWeb(web))

n

n        {

n

n          PublishingWeb _pweb = PublishingWeb.GetPublishingWeb(web);

n

n          if (_pweb != null)

n

n          {

n

n            if (_pweb.DefaultPage.Level != SPFileLevel.Checkout)

n

n            {

n

n             if (_pweb.DefaultPage.Item[FieldId.PublishingPageImage] as  ImageFieldValue == null)

n

n             {

n

n               _pweb.DefaultPage.CheckOut();

n

n               ImageFieldValue _field = new ImageFieldValue();

n

n               _field.ImageUrl = “/SiteCollectionImages/home.gif”;

n

n

n

n                                          _pweb.DefaultPage.Item[FieldId.PublishingPageImage] = _field;

n

n            _pweb.DefaultPage.Item.Update();

n

n            _pweb.DefaultPage.CheckIn(“Added Image”);

n

n            if (_pweb.PagesList.EnableMinorVersions)

n

n            {

n

n              _pweb.DefaultPage.Publish(“Published”);

n

n             }

n

n           if (_pweb.PagesList.EnableModeration)

n

n           {

n

n             _pweb.DefaultPage.Approve(“Approved!!”);

n

n           }

n

n

n

n              Console.WriteLine(“Image Added”);

n

n          }

n

n                                   

n

n         }

n

n        }

n

n       }

n

n      }

n

n     }

n

n    }

n

n    catch (Exception ex)

n

n    {

n

n      Console.WriteLine(“Error :” + ex.Message);

n

n    }

n

n

n

n       Console.ReadLine();

n

n    }

n

n  }

n

Leave a Comment