SharePoint 2010 change page content data through Object Model / API – Console Application

This took me some time on google / msdn sdk to find out, I like to share it. It is supposed to programmatically change content to existing pages.

First make a console application, set it to .NET Framework 3.5 and the build properties to x64.

This is an example that can be used to get some information about pages in the root site.

If somebody has some improvements or suggestions to make it better, I’d like to hear it.

static void ProcesPageData(string pageName, string contentType, string pageData)
{
    using (SPSite site = new SPSite("http://localhost"))
    {
        using (SPWeb web = site.OpenWeb())
        {
            //Create,retreive the publishingweb
            PublishingWeb pw = PublishingWeb.GetPublishingWeb(web);

            //Retreive all the pages
            List<PublishingPage> pages = pw.GetPublishingPages().ToList();

            //Print the page titles
            foreach (PublishingPage item in pages)
            {
                Console.WriteLine(item.Title);
            }

            //Retreive a specific page
            PublishingPage thePage = pages.Find(delegate(PublishingPage pp) { return pp.Title.Equals(pageName); });

            //If the page exists, go on
            if (thePage != null)
            {
                //If the document already is checkout to you for some reason, check it in
                try { thePage.CheckIn("Checked in through object model " + DateTime.Now.ToString()); }
                catch { }

                //Check the page out
                thePage.CheckOut();

                //For the safety check for the correct contenttype
                if (thePage.ContentType.Name.Equals(contentType))
                {
                    //Write the current data, the SiteColumns here are hardcoded: Page_Content and BottomContent in my case
                    Console.WriteLine("Page_Content: " + thePage.ListItem["Page_Content"].ToString());
                    Console.WriteLine("BottomContent: " + thePage.ListItem["BottomContent"].ToString());

                    //Overwrite the existing data
                    thePage.ListItem["Page_Content"] = pageData;

                    //Update and check it in
                    thePage.Update();
                    thePage.CheckIn("Checked in through object model " + DateTime.Now.ToString());

                    //Publish and approve the page
                    SPFile pageFile = thePage.ListItem.File;
                    pageFile.Publish("Published through object model " + DateTime.Now.ToString());
                    pageFile.Approve("Approved through object model " + DateTime.Now.ToString());

                }
            }
           Console.ReadKey();                   
        }
    }
}

This entry was posted in Geen categorie. Bookmark the permalink.

Leave a comment