From 26c142d28cf93ee4ae17e9c5cd19694db79963c0 Mon Sep 17 00:00:00 2001 From: akfakmot Date: Wed, 13 Nov 2024 16:47:20 +0100 Subject: [PATCH] Remove dependencies of Migration.Tool.Core.K11 on Migration.Tool.KXP Refactor: Remove dependencies of Migration.Tool.Core.K11 on Migration.Tool.KXP --- .../Contexts/KeyMappingContext.cs | 8 +- .../MigrateContactManagementCommandHandler.cs | 4 +- .../MigrateDataProtectionCommandHandler.cs | 3 - .../Handlers/MigrateUsersCommandHandler.cs | 2 +- Migration.Tool.Core.K11/Helpers/Printer.cs | 33 ++++--- .../K11CoreDiExtensions.cs | 6 +- .../Mappers/CmsFormMapper.cs | 83 ---------------- .../Mappers/CmsSettingsCategoryMapper.cs | 97 ------------------- .../Mappers/CmsUserMapper.cs | 56 ----------- .../Mappers/OmContactGroupMapper.cs | 32 ++++-- .../Mappers/OmContactStatusMapper.cs | 7 +- .../Migration.Tool.Core.K11.csproj | 1 - .../Services/KeyLocatorService.cs | 46 ++++----- .../Services/PrimaryKeyLocatorService.cs | 74 +++++++------- 14 files changed, 118 insertions(+), 334 deletions(-) delete mode 100644 Migration.Tool.Core.K11/Mappers/CmsFormMapper.cs delete mode 100644 Migration.Tool.Core.K11/Mappers/CmsSettingsCategoryMapper.cs delete mode 100644 Migration.Tool.Core.K11/Mappers/CmsUserMapper.cs diff --git a/Migration.Tool.Core.K11/Contexts/KeyMappingContext.cs b/Migration.Tool.Core.K11/Contexts/KeyMappingContext.cs index 4079c931..fb01a299 100644 --- a/Migration.Tool.Core.K11/Contexts/KeyMappingContext.cs +++ b/Migration.Tool.Core.K11/Contexts/KeyMappingContext.cs @@ -1,5 +1,5 @@ using System.Linq.Expressions; - +using CMS.DataEngine; using Migration.Tool.Core.K11.Services; namespace Migration.Tool.Core.K11.Contexts; @@ -11,15 +11,15 @@ public class KeyMappingContext(PrimaryKeyMappingContext primaryKeyMappingContext public MapSourceKeyResult MapSourceKey(Expression> sourceKeySelector, Expression> sourceGuidSelector, object? sourceKey, - Expression> targetKeySelector, - Expression> targetGuidSelector) where TSource : class where TTarget : class + Func targetKeySelector, + Func targetByGuidProvider) where TSource : class where TTarget : AbstractInfoBase, new() { if (sourceKey is int id && primaryKeyMappingContext.MapSourceId(sourceKeySelector, id) is { Success: true, MappedId: TTargetKey targetKey }) { return new MapSourceKeyResult(true, targetKey); } - if (keyLocatorService.TryLocate(sourceKeySelector, targetKeySelector, sourceGuidSelector, targetGuidSelector, sourceKey, out var located)) + if (keyLocatorService.TryLocate(sourceKeySelector, targetKeySelector, sourceGuidSelector, targetByGuidProvider, sourceKey, out var located)) { return new MapSourceKeyResult(true, located); } diff --git a/Migration.Tool.Core.K11/Handlers/MigrateContactManagementCommandHandler.cs b/Migration.Tool.Core.K11/Handlers/MigrateContactManagementCommandHandler.cs index 2bf62657..5e23d54b 100644 --- a/Migration.Tool.Core.K11/Handlers/MigrateContactManagementCommandHandler.cs +++ b/Migration.Tool.Core.K11/Handlers/MigrateContactManagementCommandHandler.cs @@ -178,7 +178,7 @@ private ValueInterceptorResult ContactValueInterceptor(int ordinal, string colum s => s.UserGuid, sourceUserId, t => t.MemberID, - t => t.MemberGuid + guid => MemberInfo.Provider.Get(guid) ) is { Success: true, Mapped: { } memberId }) { return ValueInterceptorResult.ReplaceValue(memberId); @@ -309,7 +309,7 @@ private ValueInterceptorResult ActivityValueInterceptor(int columnOrdinal, strin s => s.SiteGuid, sourceActivitySiteId.NullIfZero(), t => t.ChannelID, - t => t.ChannelGUID + guid => ChannelInfo.Provider.Get().WhereEquals(nameof(ChannelInfo.ChannelGUID), guid).SingleOrDefault() ); switch (result) { diff --git a/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs b/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs index 4e107eed..eec8aead 100644 --- a/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs +++ b/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs @@ -1,10 +1,8 @@ -using CMS.ContactManagement; using CMS.DataEngine; using CMS.DataProtection; using MediatR; -using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -14,7 +12,6 @@ using Migration.Tool.Core.K11.Contexts; using Migration.Tool.K11; using Migration.Tool.K11.Models; -using Migration.Tool.KXP.Context; namespace Migration.Tool.Core.K11.Handlers; diff --git a/Migration.Tool.Core.K11/Handlers/MigrateUsersCommandHandler.cs b/Migration.Tool.Core.K11/Handlers/MigrateUsersCommandHandler.cs index 5eb1f71d..2be8b4b5 100644 --- a/Migration.Tool.Core.K11/Handlers/MigrateUsersCommandHandler.cs +++ b/Migration.Tool.Core.K11/Handlers/MigrateUsersCommandHandler.cs @@ -231,7 +231,7 @@ private async Task MigrateUserRole(int k11RoleId) if (!primaryKeyMappingContext.TryRequireMapFromSource(u => u.RoleId, k11RoleId, out int xbkRoleId)) { var handbookRef = HandbookReferences - .MissingRequiredDependency(nameof(UserRoleInfo.RoleID), k11UserRole.RoleId) + .MissingRequiredDependency(nameof(UserRoleInfo.RoleID), k11UserRole.RoleId) .NeedsManualAction(); protocol.Append(handbookRef); diff --git a/Migration.Tool.Core.K11/Helpers/Printer.cs b/Migration.Tool.Core.K11/Helpers/Printer.cs index a830717a..b41e4819 100644 --- a/Migration.Tool.Core.K11/Helpers/Printer.cs +++ b/Migration.Tool.Core.K11/Helpers/Printer.cs @@ -1,10 +1,12 @@ +using CMS.ContactManagement; using CMS.DataEngine; +using CMS.DataProtection; using CMS.FormEngine; using CMS.Globalization; using CMS.MediaLibrary; using CMS.Membership; using CMS.Modules; - +using CMS.OnlineForms; using Migration.Tool.Common.Helpers; using Migration.Tool.Common.Services; using Migration.Tool.K11.Models; @@ -19,15 +21,15 @@ public static string PrintKxpModelInfo(T model) return model switch { - KXP.Models.MediaLibrary mediaLibrary => $"{currentTypeName}: {nameof(mediaLibrary.LibraryGuid)}={mediaLibrary.LibraryGuid}", - KXP.Models.MediaFile mediaFile => $"{currentTypeName}: {nameof(mediaFile.FileGuid)}={mediaFile.FileGuid}", - KXP.Models.CmsRole role => $"{currentTypeName}: {nameof(role.RoleGuid)}={role.RoleGuid}, {nameof(role.RoleName)}={role.RoleName}", - KXP.Models.CmsUser user => $"{currentTypeName}: {nameof(user.UserGuid)}={user.UserGuid}, {nameof(user.UserName)}={user.UserName}", - KXP.Models.CmsResource resource => $"{currentTypeName}: {nameof(resource.ResourceGuid)}={resource.ResourceGuid}, {nameof(resource.ResourceName)}={resource.ResourceName}", - KXP.Models.CmsSettingsCategory settingsCategory => $"{currentTypeName}: {nameof(settingsCategory.CategoryName)}={settingsCategory.CategoryName}", - KXP.Models.CmsSettingsKey settingsKey => $"{currentTypeName}: {nameof(settingsKey.KeyGuid)}={settingsKey.KeyGuid}, {nameof(settingsKey.KeyName)}={settingsKey.KeyName}", - KXP.Models.CmsForm form => $"{currentTypeName}: {nameof(form.FormGuid)}={form.FormGuid}, {nameof(form.FormName)}={form.FormName}", - KXP.Models.OmContactGroup omContactGroup => $"{currentTypeName}: {nameof(omContactGroup.ContactGroupGuid)}={omContactGroup.ContactGroupGuid}, {nameof(omContactGroup.ContactGroupName)}={omContactGroup.ContactGroupName}", + MediaLibraryInfo mediaLibrary => $"{currentTypeName}: {nameof(mediaLibrary.LibraryGUID)}={mediaLibrary.LibraryGUID}", + MediaFileInfo mediaFile => $"{currentTypeName}: {nameof(mediaFile.FileGUID)}={mediaFile.FileGUID}", + RoleInfo role => $"{currentTypeName}: {nameof(role.RoleGUID)}={role.RoleGUID}, {nameof(role.RoleName)}={role.RoleName}", + UserInfo user => $"{currentTypeName}: {nameof(user.UserGUID)}={user.UserGUID}, {nameof(user.UserName)}={user.UserName}", + ResourceInfo resource => $"{currentTypeName}: {nameof(resource.ResourceGUID)}={resource.ResourceGUID}, {nameof(resource.ResourceName)}={resource.ResourceName}", + SettingsCategoryInfo settingsCategory => $"{currentTypeName}: {nameof(settingsCategory.CategoryName)}={settingsCategory.CategoryName}", + SettingsKeyInfo settingsKey => $"{currentTypeName}: {nameof(settingsKey.KeyGUID)}={settingsKey.KeyGUID}, {nameof(settingsKey.KeyName)}={settingsKey.KeyName}", + BizFormInfo form => $"{currentTypeName}: {nameof(form.FormGUID)}={form.FormGUID}, {nameof(form.FormName)}={form.FormName}", + ContactGroupInfo omContactGroup => $"{currentTypeName}: {nameof(omContactGroup.ContactGroupGUID)}={omContactGroup.ContactGroupGUID}, {nameof(omContactGroup.ContactGroupName)}={omContactGroup.ContactGroupName}", null => $"{currentTypeName}: ", _ => $"TODO: {typeof(T).FullName}" @@ -61,12 +63,11 @@ string FormatModel(string inner) => printType RoleInfo item => FormatModel($"ID={item.RoleID}, Guid={item.RoleGUID} Name={item.RoleName}"), MemberInfo item => FormatModel($"ID={item.MemberID}, Guid={item.MemberGuid} Name={item.MemberName}"), - KXP.Models.CmsForm item => FormatModel($"ID={item.FormId}, GUID={item.FormGuid}, Name={item.FormName}"), - KXP.Models.CmsUser item => FormatModel($"ID={item.UserId}, GUID={item.UserGuid}, Name={item.UserName}"), - KXP.Models.CmsConsent item => FormatModel($"ID={item.ConsentId}, GUID={item.ConsentGuid}, Name={item.ConsentName}"), - KXP.Models.CmsConsentArchive item => FormatModel($"ID={item.ConsentArchiveId}, GUID={item.ConsentArchiveGuid}"), - KXP.Models.CmsConsentAgreement item => FormatModel($"ID={item.ConsentAgreementId}, GUID={item.ConsentAgreementGuid}"), - KXP.Models.CmsSettingsKey item => FormatModel($"ID={item.KeyId}, GUID={item.KeyGuid}, Name={item.KeyName}"), + BizFormInfo item => FormatModel($"ID={item.FormID}, GUID={item.FormGUID}, Name={item.FormName}"), + ConsentInfo item => FormatModel($"ID={item.ConsentID}, GUID={item.ConsentGuid}, Name={item.ConsentName}"), + ConsentArchiveInfo item => FormatModel($"ID={item.ConsentArchiveID}, GUID={item.ConsentArchiveGuid}"), + ConsentAgreementInfo item => FormatModel($"ID={item.ConsentAgreementID}, GUID={item.ConsentAgreementGuid}"), + SettingsKeyInfo item => FormatModel($"ID={item.KeyID}, GUID={item.KeyGUID}, Name={item.KeyName}"), CmsRole item => FormatModel($"ID={item.RoleId}, GUID={item.RoleGuid}, Name={item.RoleName}, SiteId={item.SiteId}"), CmsAttachment item => FormatModel($"ID={item.AttachmentId}, GUID={item.AttachmentGuid}, Name={item.AttachmentName}"), diff --git a/Migration.Tool.Core.K11/K11CoreDiExtensions.cs b/Migration.Tool.Core.K11/K11CoreDiExtensions.cs index 987cdb80..151d833e 100644 --- a/Migration.Tool.Core.K11/K11CoreDiExtensions.cs +++ b/Migration.Tool.Core.K11/K11CoreDiExtensions.cs @@ -1,3 +1,4 @@ +using CMS.ContactManagement; using CMS.DataEngine; using CMS.DataProtection; using CMS.FormEngine; @@ -53,13 +54,12 @@ public static IServiceCollection UseK11ToolCore(this IServiceCollection services services.AddTransient, CmsConsentArchiveMapper>(); services.AddTransient, AlternativeFormMapper>(); services.AddTransient, RoleInfoMapper>(); - services.AddTransient, CmsSettingsCategoryMapper>(); services.AddTransient, CmsSettingsKeyMapper>(); services.AddTransient, UserInfoMapper>(); services.AddTransient, MemberInfoMapper>(); services.AddTransient, UserRoleInfoMapper>(); - services.AddTransient, OmContactGroupMapper>(); - services.AddTransient, OmContactStatusMapper>(); + services.AddTransient, OmContactGroupMapper>(); + services.AddTransient, OmContactStatusMapper>(); services.AddTransient, CountryInfoMapper>(); services.AddTransient, StateInfoMapper>(); diff --git a/Migration.Tool.Core.K11/Mappers/CmsFormMapper.cs b/Migration.Tool.Core.K11/Mappers/CmsFormMapper.cs deleted file mode 100644 index e3b8e0c1..00000000 --- a/Migration.Tool.Core.K11/Mappers/CmsFormMapper.cs +++ /dev/null @@ -1,83 +0,0 @@ -using CMS.FormEngine; -using CMS.OnlineForms; - -using Microsoft.Extensions.Logging; - -using Migration.Tool.Common; -using Migration.Tool.Common.Abstractions; -using Migration.Tool.Common.MigrationProtocol; -using Migration.Tool.Core.K11.Contexts; -using Migration.Tool.K11.Models; - -namespace Migration.Tool.Core.K11.Mappers; - -public class CmsFormMapper( - ILogger logger, - PrimaryKeyMappingContext primaryKeyMappingContext, - IProtocol protocol) - : EntityMapperBase(logger, primaryKeyMappingContext, protocol) -{ - protected override BizFormInfo? CreateNewInstance(CmsForm source, MappingHelper mappingHelper, AddFailure addFailure) - { - var newBizFormInfo = BizFormInfo.New(); - newBizFormInfo.FormGUID = source.FormGuid; - return newBizFormInfo; - } - - protected override BizFormInfo MapInternal(CmsForm source, BizFormInfo target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) - { - target.FormDisplayName = source.FormDisplayName; - target.FormName = source.FormName; - target.FormItems = source.FormItems; - target.FormReportFields = source.FormReportFields; - target.FormSubmitButtonText = source.FormSubmitButtonText; - target.FormAccess = source.FormAccess.AsEnum(); - target.FormSubmitButtonImage = source.FormSubmitButtonImage; - target.FormLastModified = source.FormLastModified; - target.FormLogActivity = source.FormLogActivity.UseKenticoDefault(); - // target.FormBuilderLayout = source.FormBuilderLayout; - - if (mappingHelper.TranslateRequiredId(c => c.ClassId, source.FormClassId, out int formClassId)) - { - target.FormClassID = formClassId; - } - - return target; - } -} - -public class CmsFormMapperEf(ILogger logger, PrimaryKeyMappingContext pkContext, IProtocol protocol) : EntityMapperBase(logger, pkContext, protocol) -{ - protected override KXP.Models.CmsForm? CreateNewInstance(CmsForm source, MappingHelper mappingHelper, AddFailure addFailure) => new(); - - protected override KXP.Models.CmsForm MapInternal(CmsForm source, KXP.Models.CmsForm target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) - { - target.FormDisplayName = source.FormDisplayName; - target.FormName = source.FormName; - // target.FormSendToEmail = source.FormSendToEmail; - // target.FormSendFromEmail = source.FormSendFromEmail; - // target.FormEmailSubject = source.FormEmailSubject; - // target.FormEmailTemplate = source.FormEmailTemplate; - // target.FormEmailAttachUploadedDocs = source.FormEmailAttachUploadedDocs; - target.FormItems = source.FormItems; - target.FormReportFields = source.FormReportFields; - target.FormSubmitButtonText = source.FormSubmitButtonText; - // target.FormConfirmationEmailField = source.FormConfirmationEmailField; - // target.FormConfirmationTemplate = source.FormConfirmationTemplate; - // target.FormConfirmationSendFromEmail = source.FormConfirmationSendFromEmail; - // target.FormConfirmationEmailSubject = source.FormConfirmationEmailSubject; - target.FormAccess = source.FormAccess; - target.FormSubmitButtonImage = source.FormSubmitButtonImage; - target.FormGuid = source.FormGuid; - target.FormLastModified = source.FormLastModified; - target.FormLogActivity = source.FormLogActivity ?? false; - // target.FormBuilderLayout = source.FormBuilderLayout; - - if (mappingHelper.TranslateRequiredId(c => c.ClassId, source.FormClassId, out int classId)) - { - target.FormClassId = classId; - } - - return target; - } -} diff --git a/Migration.Tool.Core.K11/Mappers/CmsSettingsCategoryMapper.cs b/Migration.Tool.Core.K11/Mappers/CmsSettingsCategoryMapper.cs deleted file mode 100644 index 30d253c3..00000000 --- a/Migration.Tool.Core.K11/Mappers/CmsSettingsCategoryMapper.cs +++ /dev/null @@ -1,97 +0,0 @@ -using Microsoft.Extensions.Logging; - -using Migration.Tool.Common.Abstractions; -using Migration.Tool.Common.MigrationProtocol; -using Migration.Tool.Core.K11.Contexts; -using Migration.Tool.K11.Models; - -namespace Migration.Tool.Core.K11.Mappers; - -public class CmsSettingsCategoryMapper( - ILogger logger, - PrimaryKeyMappingContext pkContext, - IProtocol protocol, - IEntityMapper cmsResourceMapper) - : EntityMapperBase(logger, pkContext, protocol) -{ - protected override KXP.Models.CmsSettingsCategory? CreateNewInstance(CmsSettingsCategory source, MappingHelper mappingHelper, - AddFailure addFailure) => new(); - - - protected override KXP.Models.CmsSettingsCategory MapInternal(CmsSettingsCategory source, KXP.Models.CmsSettingsCategory target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) - { - // no category guid to match on... - if (newInstance) - { - target.CategoryOrder = source.CategoryOrder; - target.CategoryName = source.CategoryName; - target.CategoryDisplayName = source.CategoryDisplayName; - target.CategoryIdpath = source.CategoryIdpath; - target.CategoryLevel = source.CategoryLevel; - target.CategoryChildCount = source.CategoryChildCount; - target.CategoryIconPath = source.CategoryIconPath; - target.CategoryIsGroup = source.CategoryIsGroup; - target.CategoryIsCustom = source.CategoryIsCustom; - } - - if (source.CategoryResource != null) - { - if (target.CategoryResource != null && source.CategoryResourceId != null && target.CategoryResourceId != null) - { - // skip if target is present - logger.LogTrace("Skipping category resource '{ResourceGuid}', already present in target instance", target.CategoryResource.ResourceGuid); - pkContext.SetMapping(r => r.ResourceId, source.CategoryResourceId.Value, target.CategoryResourceId.Value); - } - else - { - switch (cmsResourceMapper.Map(source.CategoryResource, target.CategoryResource)) - { - case { Success: true } result: - { - target.CategoryResource = result.Item; - break; - } - case { Success: false } result: - { - addFailure(new MapperResultFailure(result.HandbookReference)); - break; - } - - default: - break; - } - } - } - else if (mappingHelper.TranslateIdAllowNulls(r => r.ResourceId, source.CategoryResourceId, out int? categoryResourceId)) - { - target.CategoryResourceId = categoryResourceId; - } - - if (source.CategoryParent != null) - { - switch (Map(source.CategoryParent, target.CategoryParent)) - { - case { Success: true } result: - { - target.CategoryParent = result.Item; - break; - } - case { Success: false } result: - { - addFailure(new MapperResultFailure(result.HandbookReference)); - break; - } - - default: - break; - } - } - else if (mappingHelper.TranslateIdAllowNulls(c => c.CategoryId, source.CategoryParentId, out int? categoryParentId)) - { - target.CategoryParentId = categoryParentId; - } - - return target; - } -} diff --git a/Migration.Tool.Core.K11/Mappers/CmsUserMapper.cs b/Migration.Tool.Core.K11/Mappers/CmsUserMapper.cs deleted file mode 100644 index 62b9b783..00000000 --- a/Migration.Tool.Core.K11/Mappers/CmsUserMapper.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Microsoft.Extensions.Logging; - -using Migration.Tool.Common.Abstractions; -using Migration.Tool.Common.MigrationProtocol; -using Migration.Tool.Core.K11.Contexts; -using Migration.Tool.K11.Models; - -namespace Migration.Tool.Core.K11.Mappers; - -public class CmsUserMapper( - ILogger logger, - PrimaryKeyMappingContext primaryKeyMappingContext, - IProtocol protocol) - : EntityMapperBase(logger, primaryKeyMappingContext, protocol) -{ - protected override KXP.Models.CmsUser CreateNewInstance(CmsUser tSourceEntity, MappingHelper mappingHelper, AddFailure addFailure) => new(); - - protected override KXP.Models.CmsUser MapInternal(CmsUser source, KXP.Models.CmsUser target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) - { - if (!newInstance && source.UserGuid != target.UserGuid) - { - // assertion failed - logger.LogTrace("Assertion failed, entity key mismatch"); - throw new InvalidOperationException("Assertion failed, entity key mismatch."); - } - - target.UserName = source.UserName; - target.FirstName = source.FirstName; - target.LastName = source.LastName; - target.Email = source.Email; - target.UserPassword = source.UserPassword; - target.UserEnabled = source.UserEnabled; - target.UserCreated = source.UserCreated; - target.LastLogon = source.LastLogon; - target.UserGuid = source.UserGuid; - target.UserLastModified = source.UserLastModified; - target.UserSecurityStamp = source.UserSecurityStamp; - target.UserAdministrationAccess = source.UserPrivilegeLevel == 3; - target.UserIsPendingRegistration = false; - target.UserPasswordLastChanged = null; - target.UserRegistrationLinkExpiration = DateTime.Now.AddDays(365); - - foreach (var sourceCmsUserRole in source.CmsUserRoles) - { - if (mappingHelper.TranslateRequiredId(r => r.RoleId, sourceCmsUserRole.RoleId, out int targetRoleId)) - { - if (target.CmsUserRoles.All(x => x.RoleId != targetRoleId)) - { - target.CmsUserRoles.Add(new KXP.Models.CmsUserRole { RoleId = targetRoleId, User = target }); - } - } - } - - return target; - } -} diff --git a/Migration.Tool.Core.K11/Mappers/OmContactGroupMapper.cs b/Migration.Tool.Core.K11/Mappers/OmContactGroupMapper.cs index a6af5473..d2d986d5 100644 --- a/Migration.Tool.Core.K11/Mappers/OmContactGroupMapper.cs +++ b/Migration.Tool.Core.K11/Mappers/OmContactGroupMapper.cs @@ -1,3 +1,4 @@ +using CMS.ContactManagement; using Microsoft.Extensions.Logging; using Migration.Tool.Common.Abstractions; @@ -11,21 +12,38 @@ public class OmContactGroupMapper( ILogger logger, PrimaryKeyMappingContext primaryKeyMappingContext, IProtocol protocol) - : EntityMapperBase(logger, primaryKeyMappingContext, protocol) + : EntityMapperBase(logger, primaryKeyMappingContext, protocol) { - protected override KXP.Models.OmContactGroup? CreateNewInstance(OmContactGroup tSourceEntity, MappingHelper mappingHelper, AddFailure addFailure) => new(); + protected override ContactGroupInfo? CreateNewInstance(OmContactGroup tSourceEntity, MappingHelper mappingHelper, AddFailure addFailure) => new(); - protected override KXP.Models.OmContactGroup MapInternal(OmContactGroup source, KXP.Models.OmContactGroup target, bool newInstance, + protected override ContactGroupInfo MapInternal(OmContactGroup source, ContactGroupInfo target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) { + T RequireValue(string propertyName, Nullable value, T defaultValue) where T : struct + { + if (value.HasValue) + { + return value.Value; + } + else + { + addFailure(new MapperResultFailure( + HandbookReferences.InvalidSourceData() + .WithMessage("Required property value is null") + .WithId(nameof(source.ContactGroupId), source.ContactGroupId) + .WithData(new { MissingProperty = propertyName }))); + return defaultValue; + } + } + target.ContactGroupName = source.ContactGroupName; target.ContactGroupDisplayName = source.ContactGroupDisplayName; target.ContactGroupDescription = source.ContactGroupDescription; target.ContactGroupDynamicCondition = source.ContactGroupDynamicCondition; - target.ContactGroupEnabled = source.ContactGroupEnabled; - target.ContactGroupLastModified = source.ContactGroupLastModified; - target.ContactGroupGuid = source.ContactGroupGuid; - target.ContactGroupStatus = source.ContactGroupStatus; + target.ContactGroupEnabled = RequireValue(nameof(source.ContactGroupEnabled), source.ContactGroupEnabled, false); + target.ContactGroupLastModified = RequireValue(nameof(source.ContactGroupLastModified), source.ContactGroupLastModified, DateTime.MinValue); + target.ContactGroupGUID = RequireValue(nameof(source.ContactGroupGuid), source.ContactGroupGuid, Guid.Empty); + target.ContactGroupStatus = (ContactGroupStatusEnum)RequireValue(nameof(source.ContactGroupStatus), source.ContactGroupStatus, 0); return target; } diff --git a/Migration.Tool.Core.K11/Mappers/OmContactStatusMapper.cs b/Migration.Tool.Core.K11/Mappers/OmContactStatusMapper.cs index 19bf2c96..ae2075ca 100644 --- a/Migration.Tool.Core.K11/Mappers/OmContactStatusMapper.cs +++ b/Migration.Tool.Core.K11/Mappers/OmContactStatusMapper.cs @@ -1,3 +1,4 @@ +using CMS.ContactManagement; using Microsoft.Extensions.Logging; using Migration.Tool.Common.Abstractions; @@ -11,12 +12,12 @@ public class OmContactStatusMapper( ILogger logger, PrimaryKeyMappingContext primaryKeyMappingContext, IProtocol protocol) - : EntityMapperBase(logger, primaryKeyMappingContext, protocol) + : EntityMapperBase(logger, primaryKeyMappingContext, protocol) { - protected override KXP.Models.OmContactStatus? CreateNewInstance(OmContactStatus tSourceEntity, MappingHelper mappingHelper, + protected override ContactStatusInfo? CreateNewInstance(OmContactStatus tSourceEntity, MappingHelper mappingHelper, AddFailure addFailure) => new(); - protected override KXP.Models.OmContactStatus MapInternal(OmContactStatus source, KXP.Models.OmContactStatus target, bool newInstance, + protected override ContactStatusInfo MapInternal(OmContactStatus source, ContactStatusInfo target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) { target.ContactStatusName = source.ContactStatusName; diff --git a/Migration.Tool.Core.K11/Migration.Tool.Core.K11.csproj b/Migration.Tool.Core.K11/Migration.Tool.Core.K11.csproj index db4305e0..391daa41 100644 --- a/Migration.Tool.Core.K11/Migration.Tool.Core.K11.csproj +++ b/Migration.Tool.Core.K11/Migration.Tool.Core.K11.csproj @@ -4,7 +4,6 @@ - diff --git a/Migration.Tool.Core.K11/Services/KeyLocatorService.cs b/Migration.Tool.Core.K11/Services/KeyLocatorService.cs index a621a42c..533e6a51 100644 --- a/Migration.Tool.Core.K11/Services/KeyLocatorService.cs +++ b/Migration.Tool.Core.K11/Services/KeyLocatorService.cs @@ -1,30 +1,40 @@ using System.Linq.Expressions; using System.Runtime.CompilerServices; - +using CMS.ContactManagement; +using CMS.DataEngine; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Migration.Tool.K11; -using Migration.Tool.KXP.Context; namespace Migration.Tool.Core.K11.Services; public class KeyLocatorService( ILogger logger, - IDbContextFactory kxpContextFactory, IDbContextFactory k11ContextFactory) { + /// + /// Finds key of target matched to source by equal GUIDs + /// + /// Type of source instance + /// Type of target instance + /// Type of target key + /// Expression that selects key from TSource instance + /// Expression that selects key from TTarget instance + /// Expression that selects GUID from TSource instance + /// Func that returns TTarget instance uniquely identified by its GUID. In case of multiple GUIDs in target dataset, it must return null + /// Source key to begin with + /// Matched target key + /// public bool TryLocate( Expression> sourceKeySelector, - Expression> targetKeySelector, + Func targetKeySelector, Expression> sourceGuidSelector, - Expression> targetGuidSelector, + Func targetByGuidProvider, object? sourceKey, out TTargetKey targetId ) where TSource : class where TTarget : class { - using var kxpContext = kxpContextFactory.CreateDbContext(); using var k11Context = k11ContextFactory.CreateDbContext(); - var sourceType = typeof(TSource); Unsafe.SkipInit(out targetId); @@ -42,24 +52,16 @@ public bool TryLocate( var sourcePredicate = Expression.Lambda>(sourceEquals, sourceKeySelector.Parameters[0]); var k11Guid = k11Context.Set().Where(sourcePredicate).Select(sourceGuidSelector).Single(); - var param = Expression.Parameter(typeof(TTarget), "t"); - var member = targetGuidSelector.Body as MemberExpression ?? throw new InvalidOperationException($"Expression SHALL NOT be other than member expression, expression: {targetGuidSelector}"); - var targetEquals = Expression.Equal( - Expression.MakeMemberAccess(param, member.Member), - Expression.Constant(k11Guid, typeof(Guid)) - ); - var targetPredicate = Expression.Lambda>(targetEquals, param); + var target = targetByGuidProvider(k11Guid); + if (target is null) + { + logger.LogWarning("Mapping {SourceFullType} primary key: {SourceId} failed, GUID {TargetGUID} not present in target instance", sourceType.FullName, sourceKey, k11Guid); + return false; + } - var query = kxpContext.Set().Where(targetPredicate); - var selector = Expression.Lambda>(targetKeySelector.Body, targetKeySelector.Parameters[0]); - targetId = query.Select(selector).Single(); + targetId = targetKeySelector(target); return true; } - catch (InvalidOperationException ioex) - { - logger.LogWarning("Mapping {SourceFullType} primary key: {SourceId} failed, {Message}", sourceType.FullName, sourceKey, ioex.Message); - return false; - } finally { if (!targetId?.Equals(default) ?? false) diff --git a/Migration.Tool.Core.K11/Services/PrimaryKeyLocatorService.cs b/Migration.Tool.Core.K11/Services/PrimaryKeyLocatorService.cs index b593263e..bdc8516d 100644 --- a/Migration.Tool.Core.K11/Services/PrimaryKeyLocatorService.cs +++ b/Migration.Tool.Core.K11/Services/PrimaryKeyLocatorService.cs @@ -1,24 +1,27 @@ using System.Linq.Expressions; - +using CMS.ContactManagement; +using CMS.ContentEngine; +using CMS.DataEngine; +using CMS.Globalization; +using CMS.Membership; +using CMS.Modules; +using CMS.OnlineForms; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Migration.Tool.Common; using Migration.Tool.K11; using Migration.Tool.K11.Models; -using Migration.Tool.KXP.Context; namespace Migration.Tool.Core.K11.Services; public class PrimaryKeyLocatorService( ILogger logger, - IDbContextFactory kxpContextFactory, IDbContextFactory k11ContextFactory) : IPrimaryKeyLocatorService { public IEnumerable SelectAll(Expression> keyNameSelector) { - using var kxpContext = kxpContextFactory.CreateDbContext(); using var k11Context = k11ContextFactory.CreateDbContext(); var sourceType = typeof(T); @@ -29,12 +32,12 @@ public IEnumerable SelectAll(Expression new { x.UserId, x.UserGuid, x.UserName }).ToList(); - var targetUsers = kxpContext.CmsUsers.Select(x => new { x.UserId, x.UserName, x.UserGuid }).ToList(); + var targetUsers = UserInfo.Provider.Get().Select(x => new { x.UserID, x.UserName, x.UserGUID }).ToList(); var result = sourceUsers.Join(targetUsers, a => new CmsUserKey(a.UserGuid, a.UserName), - b => new CmsUserKey(b.UserGuid, b.UserName), - (a, b) => new SourceTargetKeyMapping(a.UserId, b.UserId), + b => new CmsUserKey(b.UserGUID, b.UserName), + (a, b) => new SourceTargetKeyMapping(a.UserId, b.UserID), new KeyEqualityComparerWithLambda((ak, bk) => (ak?.UserGuid == bk?.UserGuid || ak?.UserName == bk?.UserName) && ak != null && bk != null) ); @@ -51,14 +54,14 @@ public IEnumerable SelectAll(Expression c.ContactCreated) .Select(x => new { x.ContactId, x.ContactGuid }).ToList(); - var target = kxpContext.OmContacts - .OrderBy(c => c.ContactCreated) - .Select(x => new { x.ContactId, x.ContactGuid }).ToList(); + var target = ContactInfo.Provider.Get() + .OrderBy(nameof(ContactInfo.ContactCreated)) + .Select(x => new { x.ContactID, x.ContactGUID }).ToList(); var result = source.Join(target, a => a.ContactGuid, - b => b.ContactGuid, - (a, b) => new SourceTargetKeyMapping(a.ContactId, b.ContactId) + b => b.ContactGUID, + (a, b) => new SourceTargetKeyMapping(a.ContactId, b.ContactID) ); foreach (var resultingMapping in result) @@ -72,12 +75,12 @@ public IEnumerable SelectAll(Expression new { x.StateId, x.StateName }).ToList(); - var target = kxpContext.CmsStates.Select(x => new { x.StateId, x.StateName }).ToList(); + var target = StateInfo.Provider.Get().Select(x => new { x.StateID, x.StateName }).ToList(); var result = source.Join(target, a => a.StateName, b => b.StateName, - (a, b) => new SourceTargetKeyMapping(a.StateId, b.StateId) + (a, b) => new SourceTargetKeyMapping(a.StateId, b.StateID) ); foreach (var resultingMapping in result) @@ -91,12 +94,12 @@ public IEnumerable SelectAll(Expression new { x.CountryId, x.CountryName }).ToList(); - var target = kxpContext.CmsCountries.Select(x => new { x.CountryId, x.CountryName }).ToList(); + var target = CountryInfo.Provider.Get().Select(x => new { x.CountryID, x.CountryName }).ToList(); var result = source.Join(target, a => a.CountryName, b => b.CountryName, - (a, b) => new SourceTargetKeyMapping(a.CountryId, b.CountryId) + (a, b) => new SourceTargetKeyMapping(a.CountryId, b.CountryID) ); foreach (var resultingMapping in result) @@ -113,8 +116,7 @@ public IEnumerable SelectAll(Expression(Expression> keyNameSelector, int sourceId, out int targetId) { - using var kxpContext = kxpContextFactory.CreateDbContext(); - using var KX12Context = k11ContextFactory.CreateDbContext(); + using var kx11Context = k11ContextFactory.CreateDbContext(); var sourceType = typeof(T); targetId = -1; @@ -122,64 +124,64 @@ public bool TryLocate(Expression> keyNameSelector, int source { if (sourceType == typeof(CmsResource)) { - var k11Guid = KX12Context.CmsResources.Where(c => c.ResourceId == sourceId).Select(x => x.ResourceGuid).Single(); - targetId = kxpContext.CmsResources.Where(x => x.ResourceGuid == k11Guid).Select(x => x.ResourceId).Single(); + var k11Guid = kx11Context.CmsResources.Where(c => c.ResourceId == sourceId).Select(x => x.ResourceGuid).Single(); + targetId = ResourceInfo.Provider.Get().WhereEquals(nameof(ResourceInfo.ResourceGUID), k11Guid).Select(x => x.ResourceID).Single(); return true; } if (sourceType == typeof(Tool.K11.Models.CmsClass)) { - var k11Guid = KX12Context.CmsClasses.Where(c => c.ClassId == sourceId).Select(x => x.ClassGuid).Single(); - targetId = kxpContext.CmsClasses.Where(x => x.ClassGuid == k11Guid).Select(x => x.ClassId).Single(); + var k11Guid = kx11Context.CmsClasses.Where(c => c.ClassId == sourceId).Select(x => x.ClassGuid).Single(); + targetId = DataClassInfoProvider.GetClasses().Where(x => x.ClassGUID == k11Guid).Select(x => x.ClassID).Single(); return true; } if (sourceType == typeof(CmsUser)) { - var k11User = KX12Context.CmsUsers.Where(c => c.UserId == sourceId).Select(x => new { x.UserGuid, x.UserName }).Single(); - targetId = kxpContext.CmsUsers.Where(x => x.UserGuid == k11User.UserGuid || x.UserName == k11User.UserName).Select(x => x.UserId).Single(); + var k11User = kx11Context.CmsUsers.Where(c => c.UserId == sourceId).Select(x => new { x.UserGuid, x.UserName }).Single(); + targetId = UserInfo.Provider.Get().WhereEquals(nameof(UserInfo.UserGUID), k11User.UserGuid).Or().WhereEquals(nameof(UserInfo.UserName), k11User.UserName).Select(x => x.UserID).Single(); return true; } if (sourceType == typeof(CmsRole)) { - var k11Role = KX12Context.CmsRoles.Where(c => c.RoleId == sourceId).Select(x => new { x.RoleGuid }).Single(); - targetId = kxpContext.CmsRoles.Where(x => x.RoleGuid == k11Role.RoleGuid).Select(x => x.RoleId).Single(); + var k11Role = kx11Context.CmsRoles.Where(c => c.RoleId == sourceId).Select(x => new { x.RoleGuid }).Single(); + targetId = RoleInfo.Provider.Get().WhereEquals(nameof(RoleInfo.RoleGUID), k11Role.RoleGuid).Select(x => x.RoleID).Single(); return true; } if (sourceType == typeof(CmsSite)) { - var k11Guid = KX12Context.CmsSites.Where(c => c.SiteId == sourceId).Select(x => x.SiteGuid).Single(); - targetId = kxpContext.CmsChannels.Where(x => x.ChannelGuid == k11Guid).Select(x => x.ChannelId).Single(); + var k11Guid = kx11Context.CmsSites.Where(c => c.SiteId == sourceId).Select(x => x.SiteGuid).Single(); + targetId = ChannelInfo.Provider.Get().WhereEquals(nameof(ChannelInfo.ChannelGUID), k11Guid).Select(x => x.ChannelID).Single(); return true; } if (sourceType == typeof(CmsState)) { - string k11CodeName = KX12Context.CmsStates.Where(c => c.StateId == sourceId).Select(x => x.StateName).Single(); - targetId = kxpContext.CmsStates.Where(x => x.StateName == k11CodeName).Select(x => x.StateId).Single(); + string k11CodeName = kx11Context.CmsStates.Where(c => c.StateId == sourceId).Select(x => x.StateName).Single(); + targetId = StateInfo.Provider.Get().WhereEquals(nameof(StateInfo.StateName), k11CodeName).Select(x => x.StateID).Single(); return true; } if (sourceType == typeof(CmsCountry)) { - string k11CodeName = KX12Context.CmsCountries.Where(c => c.CountryId == sourceId).Select(x => x.CountryName).Single(); - targetId = kxpContext.CmsCountries.Where(x => x.CountryName == k11CodeName).Select(x => x.CountryId).Single(); + string k11CodeName = kx11Context.CmsCountries.Where(c => c.CountryId == sourceId).Select(x => x.CountryName).Single(); + targetId = CountryInfo.Provider.Get().WhereEquals(nameof(CountryInfo.CountryName), k11CodeName).Select(x => x.CountryID).Single(); return true; } if (sourceType == typeof(OmContactStatus)) { - string k11Guid = KX12Context.OmContactStatuses.Where(c => c.ContactStatusId == sourceId).Select(x => x.ContactStatusName).Single(); - targetId = kxpContext.OmContactStatuses.Where(x => x.ContactStatusName == k11Guid).Select(x => x.ContactStatusId).Single(); + string k11Guid = kx11Context.OmContactStatuses.Where(c => c.ContactStatusId == sourceId).Select(x => x.ContactStatusName).Single(); + targetId = ContactStatusInfo.Provider.Get().WhereEquals(nameof(ContactStatusInfo.ContactStatusName), k11Guid).Select(x => x.ContactStatusID).Single(); return true; } if (sourceType == typeof(OmContact)) { - var k11Guid = KX12Context.OmContacts.Where(c => c.ContactId == sourceId).Select(x => x.ContactGuid).Single(); - targetId = kxpContext.OmContacts.Where(x => x.ContactGuid == k11Guid).Select(x => x.ContactId).Single(); + var k11Guid = kx11Context.OmContacts.Where(c => c.ContactId == sourceId).Select(x => x.ContactGuid).Single(); + targetId = ContactInfo.Provider.Get().WhereEquals(nameof(ContactInfo.ContactGUID), k11Guid).Select(x => x.ContactID).Single(); return true; } }