My problem

I’ve been struggling for a while to deploy my display templates.

This article does explain how to deploy the templates however when I try to redeploy the display templates the templates aren’t replaced.

Then I found some Voodoo. So now I had to put 1 and 1 together

Your solution

My feature activated

private string[] folderUrls = { "_catalogs/masterpage/Display Templates/Search/MyCustomBits" };
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{

SPSite site = properties.Feature.Parent as SPSite;
if (site != null)
{

SPWeb rootWeb = site.RootWeb;
SPList gallery = site.GetCatalog(SPListTemplateType.MasterPageCatalog);
if (gallery != null)
{

SPListItemCollection folders = gallery.Folders;
string featureId = properties.Feature.Definition.Id.ToString();
foreach (string folderUrl in folderUrls)
{

SPFolder folder = GetFolderByUrl(folders, folderUrl);
if (folder != null)
{

PublishFiles(folder, featureId);

}

}

}

}

}


and my feature deactivating

SPSite site = properties.Feature.Parent as SPSite;
if (site != null)
{

SPWeb rootWeb = site.RootWeb;
SPList gallery = site.GetCatalog(SPListTemplateType.MasterPageCatalog);
if (gallery != null)
{

SPListItemCollection folders = gallery.Folders;
string featureId = properties.Feature.Definition.Id.ToString();
foreach (string folderUrl in folderUrls)
{

SPFolder folder = GetFolderByUrl(folders, folderUrl);
if (folder != null)
{

DeleteFiles(folder, featureId);

}

}

}

}

 
So now all there is left is the Deleted and Publish files all works.

 

private static void PublishFiles(SPFolder folder, string featureId)

{

   if (folder == null)

{

          throw new ArgumentNullException(“folder”);

}

    if (String.IsNullOrEmpty(featureId))

{

          throw new ArgumentNullException(“featureId”);

}

   SPFileCollection files = folder.Files;

   var drafts = from SPFile f

                in files

                where f.Level == SPFileLevel.Draft

                select f;

    foreach (SPFile f in drafts)

{

       if (new FileInfo(f.Name).Extension == “.html”)

{

             f.Publish(“Initial Deployment”);

f.Update();

}

}

}

private static void DeleteFiles(SPFolder folder, string featureId)

{

     if (folder == null)

{

         throw new ArgumentNullException(“folder”);

}

     if (String.IsNullOrEmpty(featureId))

{

         throw new ArgumentNullException(“featureId”);

}

      SPFileCollection files = folder.Files;

      foreach (SPFile f in files)

{

          if (new FileInfo(f.Name).Extension == “.html”)

{

f.Delete();

f.Update();

}

}

}

 

Additional Note

The above solution will not work when deploying through a sand box solution

if (new FileInfo(f.Name).Extension == “.html”)

will throw an exception.

if (f.Name.Contains(“.html”))

does work for sandbox solutions

Advertisements