Created
September 6, 2017 20:47
-
-
Save sotirisf/1fcfef878570d27257fbd55164751954 to your computer and use it in GitHub Desktop.
Bulk update documents with their default template in case they have no template assigned
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Reflection; | |
using Umbraco.Core; | |
using Umbraco.Core.Logging; | |
using Umbraco.Core.Models; | |
using Umbraco.Web; | |
namespace DotSee.Common | |
{ | |
public class FixNodesWithoutTemplates : ApplicationEventHandler | |
{ | |
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) | |
{ | |
base.ApplicationStarted(umbracoApplication, applicationContext); | |
//Get a reference to the Content Type Service - we will use it to find the default template for the doctype | |
var cts = ApplicationContext.Current.Services.ContentTypeService; | |
//Get a reference to the Content Service - we will use it to update each document with its default template | |
var cs = ApplicationContext.Current.Services.ContentService; | |
//Get all content types so that we have a cached version of this to use in the foreach loop | |
var contentTypes = cts.GetAllContentTypes(); | |
LogHelper.Info(MethodBase.GetCurrentMethod().DeclaringType, "Getting list of nodes that do not have a template specified..."); | |
//Get all documents from all roots that do not have a template defined | |
foreach (IPublishedContent item in | |
new UmbracoHelper(UmbracoContext.Current) | |
.TypedContentAtRoot() | |
.SelectMany(x => x.Descendants()) | |
.Where(y => string.IsNullOrEmpty(y.GetTemplateAlias()))) | |
{ | |
//Get the document type (use the in-memory contentTypes enumerable instead of getting the content type of each doc) | |
IContentType ct = contentTypes.Where(x => x.Alias == item.ContentType.Alias).FirstOrDefault(); | |
//Get the default template for the document type | |
ITemplate t = ct.DefaultTemplate; | |
//If there is no default document, log it and move on | |
if (t == null) | |
{ | |
LogHelper.Warn(item.GetType(), string.Format("Item '{0}' of type '{1}' did not have a default template", item.Name, item.DocumentTypeAlias)); | |
continue; | |
} | |
//Create an IContent which we will update with the new template | |
IContent c = cs.GetById(item.Id); | |
//Set the template | |
c.Template = t; | |
//Publish our updated document | |
cs.SaveAndPublishWithStatus(c); | |
LogHelper.Info(item.GetType(), string.Format("Item '{0}' of type '{1}' had its template changed to '{2}'", item.Name, item.DocumentTypeAlias, t.Alias)); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment