Skip to content

Instantly share code, notes, and snippets.

@eriksimonic
Created March 14, 2019 13:12
Show Gist options
  • Save eriksimonic/6e02eae50e312a9ede13bb1c58f73f1e to your computer and use it in GitHub Desktop.
Save eriksimonic/6e02eae50e312a9ede13bb1c58f73f1e to your computer and use it in GitHub Desktop.
Fix documnet that are missing default TEmplate in umbraco. Startup Event Handler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
namespace FixDocumentTypeFuckUP
{
public class FixPublishedContentTemplates : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
var cs = applicationContext.Services.ContentTypeService;
var c = applicationContext.Services.ContentService;
foreach (var content in c.GetRootContent())
{
UpdateTemplate(content,c,cs);
}
}
private void UpdateTemplate(IContent content, IContentService contentService, IContentTypeService cs)
{
foreach (var child in contentService.GetChildren(content.Id))
{
UpdateTemplate(child, contentService, cs);
var pStatus = child.Published;
var templateId = child.Template?.Id;
if (null != templateId) continue;
var firstOrDefault = child.ContentType.AllowedTemplates.FirstOrDefault();
if (firstOrDefault == null) continue;
child.Template = firstOrDefault;
contentService.Save(child);
if(pStatus == true)
{
contentService.Publish(child, 0);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment