Saturday, September 20, 2014

Add publishing pages and web parts to the site programatically

Hi Guys

I had got the chance to work for adding the publishing pages to the given site through feature activation so that when the custom solution got deployed, the share point site is automatically associated with the custom web parts along with these publishing pages.

This is the sample code I wrote for my development purpose.
Please make sure that the publishing feature is activated on the site collection level and the site level.
In the code snippet, we need to use PublishingWeb class, which is component of Microsoft.SharePoint.Publishing.dll.
Make sure to add that dll and that namespace as well in your code to work as expected.



SPSite site = new SPSite("http://siteurl");
SPWeb web = site.OpenWeb();
//Adding AnilProgarm.aspx page to pages library
PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
PageLayout[] layouts = publishingWeb.GetAvailablePageLayouts();
PageLayout currentLayout = layouts[0];
PublishingPageCollection pages = publishingWeb.GetPublishingPages();
PublishingPage newPage = pages.Add("ANILProgram.aspx", currentLayout);
SPContentTypeCollection contentTypes = web.ContentTypes;
newPage.ListItem[FieldId.PublishingPageContent] = "THis is progragm contnet";
newPage.ListItem.Update();
newPage.Update();
newPage.CheckIn("comments updated");
view raw gistfile1.txt hosted with ❤ by GitHub

Here is the next code to add the specific web part to the existing page programatically.
Here we used the SPLimitedWebPartManager class to add the web part to the existing page.

SPSite site = new SPSite("http://siteurl/");
SPWeb web = site.OpenWeb();
SPFile file = web.GetFile(web.Url + "/Default.aspx");
SPLimitedWebPartManager limitedManager = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
ContentEditorWebPart webpart1 = new ContentEditorWebPart();
webpart1.Title = "ANIL COntent Editor";
limitedManager.AddWebPart(webpart1, "Right", 0);
view raw gistfile1.cs hosted with ❤ by GitHub

No comments: