Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate pages to content hub #278

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions KVA/Migration.Tool.Source/Handlers/MigratePagesCommandHandler.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Collections.Concurrent;
using System.Diagnostics;

using CMS.ContentEngine;
using CMS.ContentEngine.Internal;
using CMS.Core;
Expand All @@ -12,12 +11,9 @@
using CMS.Websites.Routing.Internal;
using Kentico.Xperience.UMT.Model;
using Kentico.Xperience.UMT.Services;

using MediatR;

using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;

using Migration.Tool.Common;
using Migration.Tool.Common.Abstractions;
using Migration.Tool.Common.Helpers;
Expand All @@ -30,7 +26,6 @@
using Migration.Tool.Source.Model;
using Migration.Tool.Source.Providers;
using Migration.Tool.Source.Services;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Expand Down Expand Up @@ -218,8 +213,26 @@ public async Task<CommandResult> Handle(MigratePagesCommand request, Cancellatio
var commonDataInfos = new List<ContentItemCommonDataInfo>();
foreach (var umtModel in results)
{
var result = await importer.ImportAsync(umtModel);
if (result is { Success: false })
bool isReusable = toolConfiguration.ClassNamesConvertToContentHub.Contains(targetClass?.ClassName) || targetClass?.ClassContentTypeType is ClassContentTypeType.REUSABLE;


bool skipWebPageItem = umtModel is WebPageItemModel && isReusable;

IImportResult result = new ImportResult { Success = true };
if (skipWebPageItem)
{
if (targetClass is { } && targetClass.ClassContentTypeType == ClassContentTypeType.WEBSITE)
{
targetClass.ClassContentTypeType = ClassContentTypeType.REUSABLE;
targetClass.ClassWebPageHasUrl = false;
targetClass.Update();
}
}
else
{
result = await importer.ImportAsync(umtModel);
}
if (result is { Success: false } && !skipWebPageItem)
{
logger.LogError("Failed to import: {Exception}, {ValidationResults}", result.Exception, JsonConvert.SerializeObject(result.ModelValidationResults));
}
Expand Down
11 changes: 9 additions & 2 deletions KVA/Migration.Tool.Source/Mappers/ContentItemMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,26 @@ protected override IEnumerable<IUmtModel> MapInternal(CmsTreeMapperSource source
var sourceNodeClass = modelFacade.SelectById<ICmsClass>(cmsTree.NodeClassID) ?? throw new InvalidOperationException($"Fatal: node class is missing, class id '{cmsTree.NodeClassID}'");
var mapping = classMappingProvider.GetMapping(sourceNodeClass.ClassName);
var targetClassGuid = sourceNodeClass.ClassGUID;
DataClassInfo targetClassInfo = null;
if (mapping != null)
{
targetClassGuid = DataClassInfoProvider.ProviderObject.Get(mapping.TargetClassName)?.ClassGUID ?? throw new InvalidOperationException($"Unable to find target class '{mapping.TargetClassName}'");
targetClassInfo = DataClassInfoProvider.ProviderObject.Get(mapping.TargetClassName) ?? throw new InvalidOperationException($"Unable to find target class '{mapping.TargetClassName}'");
targetClassGuid = targetClassInfo.ClassGUID;
}

bool migratedAsContentFolder = sourceNodeClass.ClassName.Equals("cms.folder", StringComparison.InvariantCultureIgnoreCase) && !configuration.UseDeprecatedFolderPageType.GetValueOrDefault(false);

var contentItemGuid = spoiledGuidContext.EnsureNodeGuid(cmsTree.NodeGUID, cmsTree.NodeSiteID, cmsTree.NodeID);

string className = targetClassInfo?.ClassName ?? sourceNodeClass.ClassName;
bool isMappedTypeReusable = targetClassInfo?.ClassContentTypeType is ClassContentTypeType.REUSABLE;
bool isReusable = configuration.ClassNamesConvertToContentHub.Contains(className) || isMappedTypeReusable;

yield return new ContentItemModel
{
ContentItemGUID = contentItemGuid,
ContentItemName = safeNodeName,
ContentItemIsReusable = false, // page is not reusable
ContentItemIsReusable = isReusable,
ContentItemIsSecured = cmsTree.IsSecuredNode ?? false,
ContentItemDataClassGuid = migratedAsContentFolder ? null : targetClassGuid,
ContentItemChannelGuid = siteGuid
Expand Down
9 changes: 9 additions & 0 deletions Migration.Tool.CLI/Migration.Tool.CLI.csproj.user
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup>
<ActiveDebugProfile>Migration</ActiveDebugProfile>
</PropertyGroup>
</Project>
3 changes: 2 additions & 1 deletion Migration.Tool.CLI/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"MigrationProtocolPath": "C:\\Logs\\protocol.txt",
"KxConnectionString": "[TODO]",
"KxCmsDirPath": "[TODO]",
"XbKDirPath": "[TODO]",
"XbKDirPath": "[TODO]",
"XbKApiSettings": {
"ConnectionStrings": {
"CMSConnectionString": "[TODO]"
Expand All @@ -29,6 +29,7 @@
"MigrateMediaToMediaLibrary": false,
"UseDeprecatedFolderPageType": false,
"CreateReusableFieldSchemaForClasses": "",
"ConvertClassesToContentHub": "",
"OptInFeatures": {
"QuerySourceInstanceApi": {
"Enabled": false,
Expand Down
1 change: 1 addition & 0 deletions Migration.Tool.Common/ConfigurationNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public class ConfigurationNames
public const string UseDeprecatedFolderPageType = "UseDeprecatedFolderPageType";

public const string ExcludeCodeNames = "ExcludeCodeNames";
public const string ConvertClassesToContentHub = "ConvertClassesToContentHub";
public const string ExplicitPrimaryKeyMapping = "ExplicitPrimaryKeyMapping";

public const string SiteName = "SiteName";
Expand Down
9 changes: 9 additions & 0 deletions Migration.Tool.Common/ToolConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,20 @@
[ConfigurationKeyName(ConfigurationNames.CreateReusableFieldSchemaForClasses)]
public string? CreateReusableFieldSchemaForClasses { get; set; }

[ConfigurationKeyName(ConfigurationNames.ConvertClassesToContentHub)]
public string? ConvertClassesToContentHub { get; set; }


public IReadOnlySet<string> ClassNamesCreateReusableSchema => classNamesCreateReusableSchema ??= new HashSet<string>(
(CreateReusableFieldSchemaForClasses?.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries) ?? []).Select(x => x.Trim()),
StringComparer.InvariantCultureIgnoreCase
);

public IReadOnlySet<string> ClassNamesConvertToContentHub => classNamesConvertToContentHub ??= new HashSet<string>(
(ConvertClassesToContentHub?.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries) ?? []).Select(x => x.Trim()),
StringComparer.InvariantCultureIgnoreCase
);

#region Opt-in features

[ConfigurationKeyName(ConfigurationNames.OptInFeatures)]
Expand All @@ -77,7 +85,7 @@

#region Connection string of target instance

[ConfigurationKeyName(ConfigurationNames.XbKConnectionString)]

Check warning on line 88 in Migration.Tool.Common/ToolConfiguration.cs

View workflow job for this annotation

GitHub Actions / Build and Test

'ConfigurationNames.XbKConnectionString' is obsolete: 'not needed anymore, connection string from Kentico config section is used'
public string XbKConnectionString
{
get => xbKConnectionString!;
Expand All @@ -97,6 +105,7 @@
#region Path to root directory of target instance

private HashSet<string>? classNamesCreateReusableSchema;
private HashSet<string>? classNamesConvertToContentHub;
private string? xbKConnectionString;

[ConfigurationKeyName(ConfigurationNames.XbKDirPath)]
Expand Down
55 changes: 55 additions & 0 deletions Migration.Tool.Extensions/ClassMappings/ClassMappingSample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,61 @@ namespace Migration.Tool.Extensions.ClassMappings;

public static class ClassMappingSample
{
public static IServiceCollection AddReusableRemodelingSample(this IServiceCollection serviceCollection)
{
const string targetClassName = "DancingGoatCore.CoffeeRemodeled";
// declare target class
var m = new MultiClassMapping(targetClassName, target =>
{
target.ClassName = targetClassName;
target.ClassTableName = "DancingGoatCore_CoffeeRemodeled";
target.ClassDisplayName = "Coffee remodeled";
target.ClassType = ClassType.CONTENT_TYPE;
target.ClassContentTypeType = ClassContentTypeType.REUSABLE;
target.ClassWebPageHasUrl = false;
});

// set new primary key
m.BuildField("CoffeeRemodeledID").AsPrimaryKey();

// change fields according to new requirements
const string sourceClassName = "DancingGoatCore.Coffee";
m
.BuildField("FarmRM")
.SetFrom(sourceClassName, "CoffeeFarm", true)
.WithFieldPatch(f => f.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Farm RM"));

m
.BuildField("CoffeeCountryRM")
.WithFieldPatch(f => f.Caption = "Country RM")
.SetFrom(sourceClassName, "CoffeeCountry", true);

m
.BuildField("CoffeeVarietyRM")
.SetFrom(sourceClassName, "CoffeeVariety", true)
.WithFieldPatch(f => f.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Variety RM"));

m
.BuildField("CoffeeProcessingRM")
.SetFrom(sourceClassName, "CoffeeProcessing", true)
.WithFieldPatch(f => f.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Processing RM"));

m
.BuildField("CoffeeAltitudeRM")
.SetFrom(sourceClassName, "CoffeeAltitude", true)
.WithFieldPatch(f => f.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "Altitude RM"));

m
.BuildField("CoffeeIsDecafRM")
.SetFrom(sourceClassName, "CoffeeIsDecaf", true)
.WithFieldPatch(f => f.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "IsDecaf RM"));

// register class mapping
serviceCollection.AddSingleton<IClassMapping>(m);

return serviceCollection;
}

public static IServiceCollection AddSimpleRemodelingSample(this IServiceCollection serviceCollection)
{
const string targetClassName = "DancingGoatCore.CoffeeRemodeled";
Expand Down
2 changes: 2 additions & 0 deletions Migration.Tool.Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ public static IServiceCollection UseCustomizations(this IServiceCollection servi
services.AddTransient<IWidgetPropertyMigration, WidgetPathSelectorMigration>();
services.AddTransient<IWidgetPropertyMigration, WidgetPageSelectorMigration>();


// services.AddClassMergeExample();
// services.AddSimpleRemodelingSample();
//services.AddReusableRemodelingSample();
// services.AddReusableSchemaIntegrationSample();
return services;
}
Expand Down
Loading