Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create Geta Categories based on existing Episerver category structure
using System.Collections.Generic;
using System.Linq;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.PlugIn;
using EPiServer.Scheduler;
using Foundation.Cms.Categories;
using Geta.EpiCategories;
using Geta.EpiCategories.Extensions;
namespace Foundation.CategoryMigration
{
[ScheduledPlugIn(
DisplayName = "Create Geta Categories based on existing Episerver category structure"
, Description = "Create Geta Categories based on existing Episerver category structure"
, SortIndex = int.MaxValue)]
public class CreateGetaCategoriesFromEpiserverCategoriesJob : ScheduledJobBase
{
private readonly CategoryRepository _categoryRepository;
private readonly IContentRepository _contentRepository;
private bool _stopSignaled;
private int _categoryCounterTotal = 0;
private int _categoryCounterCreated = 0;
private IList<Category> _allCategories;
public CreateGetaCategoriesFromEpiserverCategoriesJob(CategoryRepository categoryRepository, IContentRepository repo)
{
IsStoppable = true;
_categoryRepository = categoryRepository;
_contentRepository = repo;
}
public override void Stop()
{
_stopSignaled = true;
}
public override string Execute()
{
OnStatusChanged($"Starting execution of {this.GetType()}");
_allCategories = new List<Category>();
foreach (var category in _categoryRepository.GetRoot().GetList())
{
_allCategories.Add(category as Category);
}
IterateCategories(_categoryRepository.GetRoot(), _contentRepository.GetOrCreateGlobalCategoriesRoot());
return $"{_categoryCounterTotal} categories checked, {_categoryCounterCreated} categories created";
}
private void IterateCategories(Category currentParent, ContentReference parentCategory)
{
var categories = _allCategories.Where(x => x.Parent.ID == currentParent.ID).ToList();
foreach (var category in categories)
{
if (_stopSignaled) break;
OnStatusChanged($"Working on category {category.Name}, child of: {currentParent.Name}");
var currentCategory = GetOrCreateCategory<StandardCategory>(category, parentCategory);
IterateCategories(category, currentCategory.ContentLink);
}
}
private T GetOrCreateCategory<T>(Category category, ContentReference parentCategory) where T : CategoryData
{
_categoryCounterTotal++;
var categories = _contentRepository.GetChildren<T>(parentCategory);
foreach (var categoryExisting in categories)
{
if (_stopSignaled) break;
if (categoryExisting.Name.Equals(category.Name))
{
return categoryExisting;
}
}
_categoryCounterCreated++;
var categoryNew = _contentRepository.GetDefault<T>(parentCategory);
categoryNew.Name = category.Name;
categoryNew.Description = category.Description;
_contentRepository.Publish(categoryNew);
return categoryNew;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.