Sunday, April 24, 2011

Deleting layout from layout gallery

When we want to delete a particular layout from layout gallery and it is being referred by pages (pages created by this layout), we will not be able to delete the layout. It will redirect us to error page stating-"This item cannot be deleted because it is still referenced by other pages." So, to remove the layout, we will have to remove all the pages which are referring the layout and then we will be able to remove the layout. Alternatively, we can move the layout to a temporary folder by opening the master page gallery in window explorer and then remove the temporary folder. Moving a layout to a different folder will break all the page references and therefore removing the layout will not create any problem.
This we can also do through code as below-

private static void DeleteLayoutFromGallery(SPWeb web, string layoutName)
SPFile layout = web.GetFile(web.Site.Url.ToString() + "/_catalogs/masterpage/" + layoutName);
SPFolder layoutFolder = layout.ParentFolder;
SPFolder tempFolder = layoutFolder.SubFolders.Add("tempFolder");
layout.MoveTo(tempFolder.Url + "/" + layout.Name);

The important point to note is- All the pages refering the deleted layout will not get the layout reference and hence will get corrupted. Even if we re-add those layouts through feature, broken references will still be broken and pages will remain be corrupted. If we will try to open those pages, It will display error message reading- "Resource can not be found."

Show only required layouts in available layout gallery - PublishingWeb.SetAvailablePageLayouts method

SharePoint have few out of the box layouts available with publishing site template. When we create a new publishing layout, that layout need to be added into the available layout gallery in order to make it available to user for creating the publishing page. This can be done through mannual steps as well as through code. SharePoint object model have PublishingWeb.SetAvailablePageLayouts() method which can be use to set available layouts. Here is how-

using(SPSite site=new SPSite(url))
PublishingSite pubSite=new PublishingSite(site);
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(site.OpenWeb());
SPContentType associatedCType = pubSite.ContentTypes["My ContentType"];
if (associatedCType != null)
PageLayoutCollection allLayouts = pubSite.GetPageLayouts(associatedCType, true);
pubWeb.SetAvailablePageLayouts(allLayouts.ToArray(), true);

Thats it. The above piece of code will add all the layouts inheriting from content type associatedCType and remove all other layouts from the available layout gallery. Only added layouts will be available for creating pages