Upgrading publishing masterpages in SharePoint 2010

If you worked on the SharePoint 2010 site sustainment project, you know that in SharePoint Publishing, when provisioning a file in a module and existing file already exists in the underlying library, you will receive an error.

In my case, I’ve got a file called MyCustom.master, which is has been deployed to my master page gallery. Now that I’m trying to upgrade the file, I want to push the new version to my master page gallery.

Here is the definition in my module:

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
	<Module Name="MasterPage" List="116" Url="_catalogs/masterpage">
		<File Path="MasterPage\MyCustom.master" Url="MyCustom.master"
		IgnoreIfAlreadyExists="True" Type="GhostableInLibrary"/>
</Module>
</Elements>

IgnoreIfAlreadyExists, seems to do the trick but it doesn’t help with overwriting the file if it already exists. When you set it to True is ignores the conflict and doesn’t copy a new version of the file. “False” gives an error during the deployment and doesn’t upgrade the file.

Here is the code which I added to the feature receiver provisioning my masterpage to force the upgrade manually.

SPWeb spweb = properties.Feature.Parent as SPWeb;
SPFile file = spweb.GetFile("_catalogs/masterpage/MyCustom.master");
SPFolder folder = spweb.Lists["Master Page Gallery"].RootFolder;

if (file.CheckedOutByUser != null)
{
    file.CheckIn("checking in");
}

file.CheckOut();
string directory = properties.Feature.Definition.RootDirectory;
string[] masterpages = Directory.GetFiles(directory + @"\masterpage", "MyCustom.master",
System.IO.SearchOption.TopDirectoryOnly);
FileInfo fileInfo = new FileInfo(masterpages[0]);
byte[] bytes = System.IO.File.ReadAllBytes(masterpages[0]);
folder.Files.Add(fileInfo.Name, bytes, true);
file.Update();
file.CheckIn("Checked in by receiver");
file.Publish("Published by receiver");
file.Approve("Approved receiver");

Essentially, it checks for a file in a feature module (my new version of masterpage), and adds the file to the master page gallery. It also checks in and publishes a new version.

Now my upgrade works without complaints.

Enjoy!

This entry was posted in sharepoint, sharepoint 2010 and tagged , . Bookmark the permalink.

Comments are closed.