Tuesday, April 12, 2011

How to delete a Page layout in Master page and layouts library in SharePoint

Today I was working on solution based on Publishing pages. On activating a feature, a new page layout will be deployed to the Master page and layouts document library. On the other way, when I deactivate the feature the solution should delete the deployed page layout and associated content types etc so that I can ensure that no turds are left in the farm.

But to my surprise I was not able to delete the page layouts I created either through code or manually in the document library. It was throwing a very misguiding error "Server error: This item cannot be deleted because it is still referenced by other pages".. After spending a hour or so I figured that there is no page in my site referencing this Page Layout.  Microsoft has confirmed that its a bug in MOSS 2007 thats sometimes the page layout cannot be deleted.

But how do I delete it then?. There is a trick to do it.
1. Open the Master page gallery in windows explorer mode.
2. Create a subfolder and name it 'Delete' (you can give any name to it).
3. Cut and paste your layout.aspx page to the folder.
4. Delete the folder now.

So we confirmed that manually we were able to delete the page layouts. Lets try it programmatically.

SPWeb web=properties.Feature.Parent as SPWeb;
SPSite sitecollection= web.site;
PublishingWeb web=PublishingWeb.GetPublishingWeb(web);
SPFolderCollection folders=web.Lists["Master Page Gallery"].RootFolder.SubFolders;
SPFolder folder =folder.add("Delete");
PublishingSite psite=new PublishingSite(sitecollection);
SPContentType ctype=psite.ContentTypes["SampleCType"];
PageLayoutCollection pagelayouts=psite.GetPageLayouts(ctype,true);
PageLayout layout=pagelayouts["/_catalogs/masterpage/SampleLayout.aspx"];
layout.ListItem.File.MoveTo(folder.url+"/SampleLayout.aspx");
folder.Delete();



No comments:

Post a Comment