Friday, August 28, 2015

Overwriting ghostable files in SharePoint 2013 libraries using feature elements (no code)



One of the cool new changes or rather additions to the feature framework in SharePoint 2013 is the ability to overwrite files in document libraries. Which was never possible declaratively via file elements in modules. All we could do is set the attribute IgnoreIfAlreadyExists="TRUE" so SharePoint doesn’t freak out if the file already existed in the library but it never allowed us to replace the file.
For example the following module deploys sample.txt to a document library called Shared Documents:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="FileDeployTest" Url="Shared Documents" List="101" >
    <File Path="FileDeployTest\Sample.txt" Url="Sample.txt" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" />
  </Module>
</Elements>

If you have a copy of Sample.txt in that library already, you will not be able to overwrite it. This is an annoying issue especially if you have developed a feature that implements your UI branding (masterpages, layout pages & style sheets). Unless you deploy your feature using Visual Studio (which no body does that in production env.) you will not be able to replace existing UI files.
Developers have gotten around this through implementing a feature receiver that will do the job. A lot of these solutions are now available on the web so I’m not going to expand further on that.
The good news is that we have introduced a new attribute to the file element (undocumented yet) that allows to overwrite existing ghostable files in SharePoint libraries. The attribute is ReplaceContent="True". If you set that attribute to True SharePoint will replace your file if it already exists. So your module should look like this:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="FileDeployTest" Url="Shared Documents" List="101" >
    <File Path="FileDeployTest\Sample.txt" Url="Sample.txt" Type="GhostableInLibrary" ReplaceContent="True"/>
  </Module>
</Elements>

One thing to be careful with though, if the document or file you are trying to replace is checked out by a different user, other than the user you are using to activate the feature, the feature activation will fail with the following error:
The file is currently checked out or locked for editing by another user.
So that’s something you need to watch out for especially when dealing with master pages and layout pages for example since the master page library requires checkout by default and maybe some get checked out by others.
I also want to mention that if the library requires check out or approval, SharePoint will take care of that for you. So no worries on that end.

No comments:

Post a Comment