From 60f817b18c3e2a143a634fd362f2feaafed4e3a4 Mon Sep 17 00:00:00 2001 From: akfakmot Date: Wed, 13 Nov 2024 09:06:40 +0100 Subject: [PATCH 1/4] Remove Migration.Tool.KXP dependency from MigrateContactManagementCommandHandler Refactor: Remove Migration.Tool.KXP dependency from MigrateContactManagementCommandHandler --- .../MigrateContactManagementCommandHandler.cs | 140 +++++++++--------- 1 file changed, 66 insertions(+), 74 deletions(-) diff --git a/Migration.Tool.Core.K11/Handlers/MigrateContactManagementCommandHandler.cs b/Migration.Tool.Core.K11/Handlers/MigrateContactManagementCommandHandler.cs index b2c864a5..2bf62657 100644 --- a/Migration.Tool.Core.K11/Handlers/MigrateContactManagementCommandHandler.cs +++ b/Migration.Tool.Core.K11/Handlers/MigrateContactManagementCommandHandler.cs @@ -1,10 +1,10 @@ using CMS.Activities; using CMS.ContactManagement; using CMS.ContentEngine; - +using CMS.Globalization; +using CMS.Membership; using MediatR; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Migration.Tool.Common; @@ -17,14 +17,11 @@ using Migration.Tool.Core.K11.Services; using Migration.Tool.K11.Models; using Migration.Tool.KXP.Api; -using Migration.Tool.KXP.Context; -using Migration.Tool.KXP.Models; namespace Migration.Tool.Core.K11.Handlers; public class MigrateContactManagementCommandHandler( ILogger logger, - IDbContextFactory kxpContextFactory, BulkDataCopyService bulkDataCopyService, ToolConfiguration toolConfiguration, PrimaryKeyMappingContext primaryKeyMappingContext, @@ -33,12 +30,8 @@ public class MigrateContactManagementCommandHandler( KxpClassFacade kxpClassFacade, ISpoiledGuidContext spoiledGuidContext, IProtocol protocol) - : IRequestHandler, IDisposable + : IRequestHandler { - private readonly KxpContext kxpContext = kxpContextFactory.CreateDbContext(); - - public void Dispose() => kxpContext.Dispose(); - public Task Handle(MigrateContactManagementCommand request, CancellationToken cancellationToken) { countryMigrator.MigrateCountriesAndStates(); @@ -62,35 +55,35 @@ public Task Handle(MigrateContactManagementCommand request, Cance { var requiredColumnsForContactMigration = new Dictionary { - { nameof(Tool.K11.Models.OmContact.ContactId), nameof(KXP.Models.OmContact.ContactId) }, - { nameof(Tool.K11.Models.OmContact.ContactFirstName), nameof(KXP.Models.OmContact.ContactFirstName) }, - { nameof(Tool.K11.Models.OmContact.ContactMiddleName), nameof(KXP.Models.OmContact.ContactMiddleName) }, - { nameof(Tool.K11.Models.OmContact.ContactLastName), nameof(KXP.Models.OmContact.ContactLastName) }, - { nameof(Tool.K11.Models.OmContact.ContactJobTitle), nameof(KXP.Models.OmContact.ContactJobTitle) }, - { nameof(Tool.K11.Models.OmContact.ContactAddress1), nameof(KXP.Models.OmContact.ContactAddress1) }, - { nameof(Tool.K11.Models.OmContact.ContactCity), nameof(KXP.Models.OmContact.ContactCity) }, - { nameof(Tool.K11.Models.OmContact.ContactZip), nameof(KXP.Models.OmContact.ContactZip) }, - { nameof(Tool.K11.Models.OmContact.ContactStateId), nameof(KXP.Models.OmContact.ContactStateId) }, - { nameof(Tool.K11.Models.OmContact.ContactCountryId), nameof(KXP.Models.OmContact.ContactCountryId) }, - { nameof(Tool.K11.Models.OmContact.ContactMobilePhone), nameof(KXP.Models.OmContact.ContactMobilePhone) }, - { nameof(Tool.K11.Models.OmContact.ContactBusinessPhone), nameof(KXP.Models.OmContact.ContactBusinessPhone) }, - { nameof(Tool.K11.Models.OmContact.ContactEmail), nameof(KXP.Models.OmContact.ContactEmail) }, + { nameof(OmContact.ContactId), nameof(ContactInfo.ContactID) }, + { nameof(OmContact.ContactFirstName), nameof(ContactInfo.ContactFirstName) }, + { nameof(OmContact.ContactMiddleName), nameof(ContactInfo.ContactMiddleName) }, + { nameof(OmContact.ContactLastName), nameof(ContactInfo.ContactLastName) }, + { nameof(OmContact.ContactJobTitle), nameof(ContactInfo.ContactJobTitle) }, + { nameof(OmContact.ContactAddress1), nameof(ContactInfo.ContactAddress1) }, + { nameof(OmContact.ContactCity), nameof(ContactInfo.ContactCity) }, + { nameof(OmContact.ContactZip), nameof(ContactInfo.ContactZIP) }, + { nameof(OmContact.ContactStateId), nameof(ContactInfo.ContactStateID) }, + { nameof(OmContact.ContactCountryId), nameof(ContactInfo.ContactCountryID) }, + { nameof(OmContact.ContactMobilePhone), nameof(ContactInfo.ContactMobilePhone) }, + { nameof(OmContact.ContactBusinessPhone), nameof(ContactInfo.ContactBusinessPhone) }, + { nameof(OmContact.ContactEmail), nameof(ContactInfo.ContactEmail) }, // No support 2022-07-07 { nameof(OmContact.ContactBirthday), nameof(KXO.Models.OmContact.ContactBirthday) }, - { nameof(Tool.K11.Models.OmContact.ContactGender), nameof(KXP.Models.OmContact.ContactGender) }, + { nameof(OmContact.ContactGender), nameof(ContactInfo.ContactGender) }, // { nameof(OmContact.ContactStatusId), nameof(KXO.Models.OmContact.ContactStatusId) }, // No support 2022-07-07 but needs to be mapped because of constraint - { nameof(Tool.K11.Models.OmContact.ContactNotes), nameof(KXP.Models.OmContact.ContactNotes) }, - { nameof(Tool.K11.Models.OmContact.ContactOwnerUserId), nameof(KXP.Models.OmContact.ContactOwnerUserId) }, + { nameof(OmContact.ContactNotes), nameof(ContactInfo.ContactNotes) }, + { nameof(OmContact.ContactOwnerUserId), nameof(ContactInfo.ContactOwnerUserID) }, // No support 2022-07-07 { nameof(OmContact.ContactMonitored), nameof(KXO.Models.OmContact.ContactMonitored) }, - { nameof(Tool.K11.Models.OmContact.ContactGuid), nameof(KXP.Models.OmContact.ContactGuid) }, - { nameof(Tool.K11.Models.OmContact.ContactLastModified), nameof(KXP.Models.OmContact.ContactLastModified) }, - { nameof(Tool.K11.Models.OmContact.ContactCreated), nameof(KXP.Models.OmContact.ContactCreated) }, + { nameof(OmContact.ContactGuid), nameof(ContactInfo.ContactGUID) }, + { nameof(OmContact.ContactLastModified), nameof(ContactInfo.ContactLastModified) }, + { nameof(OmContact.ContactCreated), nameof(ContactInfo.ContactCreated) }, // No support 2022-07-07 { nameof(OmContact.ContactBounces), nameof(KXO.Models.OmContact.ContactBounces) }, - { nameof(Tool.K11.Models.OmContact.ContactCampaign), nameof(KXP.Models.OmContact.ContactCampaign) }, + { nameof(OmContact.ContactCampaign), nameof(ContactInfo.ContactCampaign) }, // No support 2022-07-07 { nameof(OmContact.ContactSalesForceLeadId), nameof(KXO.Models.OmContact.ContactSalesForceLeadId) }, // No support 2022-07-07 { nameof(OmContact.ContactSalesForceLeadReplicationDisabled), nameof(KXO.Models.OmContact.ContactSalesForceLeadReplicationDisabled) }, // No support 2022-07-07 { nameof(OmContact.ContactSalesForceLeadReplicationDateTime), nameof(KXO.Models.OmContact.ContactSalesForceLeadReplicationDateTime) }, // No support 2022-07-07 { nameof(OmContact.ContactSalesForceLeadReplicationSuspensionDateTime), nameof(KXO.Models.OmContact.ContactSalesForceLeadReplicationSuspensionDateTime) }, - { nameof(Tool.K11.Models.OmContact.ContactCompanyName), nameof(KXP.Models.OmContact.ContactCompanyName) } + { nameof(OmContact.ContactCompanyName), nameof(ContactInfo.ContactCompanyName) } // No support 2022-07-07 { nameof(OmContact.ContactSalesForceLeadReplicationRequired), nameof(KXO.Models.OmContact.ContactSalesForceLeadReplicationRequired) }, }; @@ -119,9 +112,9 @@ public Task Handle(MigrateContactManagementCommand request, Cance } } - primaryKeyMappingContext.PreloadDependencies(u => u.UserId); - primaryKeyMappingContext.PreloadDependencies(u => u.StateId); - primaryKeyMappingContext.PreloadDependencies(u => u.CountryId); + primaryKeyMappingContext.PreloadDependencies(u => u.UserId); + primaryKeyMappingContext.PreloadDependencies(u => u.StateId); + primaryKeyMappingContext.PreloadDependencies(u => u.CountryId); var bulkCopyRequest = new BulkCopyRequest("OM_Contact", s => true, // s => s != "ContactID", @@ -149,7 +142,7 @@ public Task Handle(MigrateContactManagementCommand request, Cance private ValueInterceptorResult ContactValueInterceptor(int ordinal, string columnName, object value, Dictionary currentRow) { - if (columnName.Equals(nameof(KXP.Models.OmContact.ContactCompanyName), StringComparison.InvariantCultureIgnoreCase)) + if (columnName.Equals(nameof(ContactInfo.ContactCompanyName), StringComparison.InvariantCultureIgnoreCase)) { // autofix removed in favor of error report and data consistency // var truncatedValue = SqlDataTypeHelper.TruncateString(value, 100); @@ -171,27 +164,27 @@ private ValueInterceptorResult ContactValueInterceptor(int ordinal, string colum } } - if (columnName.Equals(nameof(KXP.Models.OmContact.ContactOwnerUserId), StringComparison.InvariantCultureIgnoreCase) && value is int sourceUserId) + if (columnName.Equals(nameof(ContactInfo.ContactOwnerUserID), StringComparison.InvariantCultureIgnoreCase) && value is int sourceUserId) { - switch (primaryKeyMappingContext.MapSourceId(u => u.UserId, sourceUserId)) + switch (primaryKeyMappingContext.MapSourceId(u => u.UserId, sourceUserId)) { case (true, var id): return ValueInterceptorResult.ReplaceValue(id); case { Success: false }: { // try search member - if (keyMappingContext.MapSourceKey( + if (keyMappingContext.MapSourceKey( s => s.UserId, s => s.UserGuid, sourceUserId, - t => t.MemberId, + t => t.MemberID, t => t.MemberGuid ) is { Success: true, Mapped: { } memberId }) { return ValueInterceptorResult.ReplaceValue(memberId); } - protocol.Append(HandbookReferences.MissingRequiredDependency(columnName, value) + protocol.Append(HandbookReferences.MissingRequiredDependency(columnName, value) .WithData(currentRow)); return ValueInterceptorResult.SkipRow; } @@ -201,15 +194,15 @@ private ValueInterceptorResult ContactValueInterceptor(int ordinal, string colum } } - if (columnName.Equals(nameof(KXP.Models.OmContact.ContactStateId), StringComparison.InvariantCultureIgnoreCase) && value is int sourceStateId) + if (columnName.Equals(nameof(ContactInfo.ContactStateID), StringComparison.InvariantCultureIgnoreCase) && value is int sourceStateId) { - switch (primaryKeyMappingContext.MapSourceId(u => u.StateId, sourceStateId.NullIfZero())) + switch (primaryKeyMappingContext.MapSourceId(u => u.StateId, sourceStateId.NullIfZero())) { case (true, var id): return ValueInterceptorResult.ReplaceValue(id); case { Success: false }: { - protocol.Append(HandbookReferences.MissingRequiredDependency(columnName, value) + protocol.Append(HandbookReferences.MissingRequiredDependency(columnName, value) .WithData(currentRow)); return ValueInterceptorResult.SkipRow; } @@ -219,15 +212,15 @@ private ValueInterceptorResult ContactValueInterceptor(int ordinal, string colum } } - if (columnName.Equals(nameof(KXP.Models.OmContact.ContactCountryId), StringComparison.InvariantCultureIgnoreCase) && value is int sourceCountryId) + if (columnName.Equals(nameof(ContactInfo.ContactCountryID), StringComparison.InvariantCultureIgnoreCase) && value is int sourceCountryId) { - switch (primaryKeyMappingContext.MapSourceId(u => u.CountryId, sourceCountryId.NullIfZero())) + switch (primaryKeyMappingContext.MapSourceId(u => u.CountryId, sourceCountryId.NullIfZero())) { case (true, var id): return ValueInterceptorResult.ReplaceValue(id); case { Success: false }: { - protocol.Append(HandbookReferences.MissingRequiredDependency(columnName, value) + protocol.Append(HandbookReferences.MissingRequiredDependency(columnName, value) .WithData(currentRow)); return ValueInterceptorResult.SkipRow; } @@ -244,30 +237,29 @@ private ValueInterceptorResult ContactValueInterceptor(int ordinal, string colum #endregion #region "Migrate contact activities" - private CommandResult? MigrateContactActivities() { var requiredColumnsForContactMigration = new Dictionary { - { nameof(Tool.K11.Models.OmActivity.ActivityId), nameof(KXP.Models.OmActivity.ActivityId) }, - { nameof(Tool.K11.Models.OmActivity.ActivityContactId), nameof(KXP.Models.OmActivity.ActivityContactId) }, - { nameof(Tool.K11.Models.OmActivity.ActivityCreated), nameof(KXP.Models.OmActivity.ActivityCreated) }, - { nameof(Tool.K11.Models.OmActivity.ActivityType), nameof(KXP.Models.OmActivity.ActivityType) }, - // No support 2022-07-07 { nameof(OmActivity.ActivityItemId), nameof(KXO.Models.OmActivity.ActivityItemId) }, - // No support 2022-07-07 { nameof(OmActivity.ActivityItemDetailId), nameof(KXO.Models.OmActivity.ActivityItemDetailId) }, - { nameof(Tool.K11.Models.OmActivity.ActivityValue), nameof(KXP.Models.OmActivity.ActivityValue) }, - { nameof(Tool.K11.Models.OmActivity.ActivityUrl), nameof(KXP.Models.OmActivity.ActivityUrl) }, - { nameof(Tool.K11.Models.OmActivity.ActivityTitle), nameof(KXP.Models.OmActivity.ActivityTitle) }, - { nameof(Tool.K11.Models.OmActivity.ActivitySiteId), nameof(KXP.Models.OmActivity.ActivityChannelId) }, - { nameof(Tool.K11.Models.OmActivity.ActivityComment), nameof(KXP.Models.OmActivity.ActivityComment) }, - // { nameof(OmActivity.ActivityCampaign), nameof(KXP.Models.OmActivity.ActivityCampaign) }, // deprecated without replacement in v27 - { nameof(Tool.K11.Models.OmActivity.ActivityUrlreferrer), nameof(KXP.Models.OmActivity.ActivityUrlreferrer) }, - { nameof(Tool.K11.Models.OmActivity.ActivityCulture), nameof(KXP.Models.OmActivity.ActivityLanguageId) }, - { nameof(Tool.K11.Models.OmActivity.ActivityNodeId), nameof(KXP.Models.OmActivity.ActivityWebPageItemGuid) }, - { nameof(Tool.K11.Models.OmActivity.ActivityUtmsource), nameof(KXP.Models.OmActivity.ActivityUtmsource) }, + { nameof(OmActivity.ActivityId), nameof(ActivityInfo.ActivityID) }, + { nameof(OmActivity.ActivityContactId), nameof(ActivityInfo.ActivityContactID) }, + { nameof(OmActivity.ActivityCreated), nameof(ActivityInfo.ActivityCreated) }, + { nameof(OmActivity.ActivityType), nameof(ActivityInfo.ActivityType) }, + // No support 2022-07-07 { nameof(OmActivity.ActivityItemID), nameof(KXO.Models.OmActivity.ActivityItemID) }, + // No support 2022-07-07 { nameof(OmActivity.ActivityItemDetailID), nameof(KXO.Models.OmActivity.ActivityItemDetailID) }, + { nameof(OmActivity.ActivityValue), nameof(ActivityInfo.ActivityValue) }, + { nameof(OmActivity.ActivityUrl), nameof(ActivityInfo.ActivityURL) }, + { nameof(OmActivity.ActivityTitle), nameof(ActivityInfo.ActivityTitle) }, + { nameof(OmActivity.ActivitySiteId), nameof(ActivityInfo.ActivityChannelID) }, + { nameof(OmActivity.ActivityComment), nameof(ActivityInfo.ActivityComment) }, + // { nameof(OmActivity.ActivityCampaign), nameof(ActivityInfo.ActivityCampaign) }, // deprecated without replacement in v27 + { nameof(OmActivity.ActivityUrlreferrer), nameof(ActivityInfo.ActivityURLReferrer) }, + { nameof(OmActivity.ActivityCulture), nameof(ActivityInfo.ActivityLanguageID) }, + { nameof(OmActivity.ActivityNodeId), nameof(ActivityInfo.ActivityWebPageItemGUID) }, + { nameof(OmActivity.ActivityUtmsource), nameof(ActivityInfo.ActivityUTMSource) }, // No support 2022-07-07 { nameof(OmActivity.ActivityAbvariantName), nameof(KXO.Models.OmActivity.ActivityAbvariantName) }, - // OBSOLETE 26.0.0: { nameof(OmActivity.ActivityUrlhash), nameof(KXP.Models.OmActivity.ActivityUrlhash) }, - { nameof(Tool.K11.Models.OmActivity.ActivityUtmcontent), nameof(KXP.Models.OmActivity.ActivityUtmcontent) } + // OBSOLETE 26.0.0: { nameof(OmActivity.ActivityUrlhash), nameof(ActivityInfo.ActivityUrlhash) }, + { nameof(OmActivity.ActivityUtmcontent), nameof(ActivityInfo.ActivityUTMContent) } }; foreach (var cfi in kxpClassFacade.GetCustomizedFieldInfos(ActivityInfo.TYPEINFO.ObjectClassName)) @@ -309,15 +301,15 @@ private ValueInterceptorResult ContactValueInterceptor(int ordinal, string colum private ValueInterceptorResult ActivityValueInterceptor(int columnOrdinal, string columnName, object value, Dictionary currentRow) { - if (columnName.Equals(nameof(Tool.K11.Models.OmActivity.ActivitySiteId), StringComparison.InvariantCultureIgnoreCase) && + if (columnName.Equals(nameof(OmActivity.ActivitySiteId), StringComparison.InvariantCultureIgnoreCase) && value is int sourceActivitySiteId) { - var result = keyMappingContext.MapSourceKey( + var result = keyMappingContext.MapSourceKey( s => s.SiteId, s => s.SiteGuid, sourceActivitySiteId.NullIfZero(), - t => t.ChannelId, - t => t.ChannelGuid + t => t.ChannelID, + t => t.ChannelGUID ); switch (result) { @@ -336,7 +328,7 @@ private ValueInterceptorResult ActivityValueInterceptor(int columnOrdinal, strin case AutofixEnum.Error: default: //error protocol.Append(HandbookReferences - .MissingRequiredDependency(columnName, value) + .MissingRequiredDependency(columnName, value) .WithData(currentRow) ); return ValueInterceptorResult.SkipRow; @@ -348,9 +340,9 @@ private ValueInterceptorResult ActivityValueInterceptor(int columnOrdinal, strin } } - if (columnName.Equals(nameof(Tool.K11.Models.OmActivity.ActivityNodeId), StringComparison.InvariantCultureIgnoreCase) && value is int activityNodeId) + if (columnName.Equals(nameof(OmActivity.ActivityNodeId), StringComparison.InvariantCultureIgnoreCase) && value is int activityNodeId) { - if (currentRow.TryGetValue(nameof(Tool.K11.Models.OmActivity.ActivitySiteId), out object? mSiteId) && mSiteId is int siteId) + if (currentRow.TryGetValue(nameof(OmActivity.ActivitySiteId), out object? mSiteId) && mSiteId is int siteId) { if (spoiledGuidContext.GetNodeGuid(siteId, activityNodeId) is { } nodeGuid) { @@ -369,14 +361,14 @@ private ValueInterceptorResult ActivityValueInterceptor(int columnOrdinal, strin case AutofixEnum.Error: default: //error protocol.Append(HandbookReferences - .MissingRequiredDependency(columnName, value) + .MissingRequiredDependency(columnName, value) .WithData(currentRow) ); return ValueInterceptorResult.SkipRow; } } - if (columnName.Equals(nameof(KXP.Models.OmActivity.ActivityLanguageId), StringComparison.InvariantCultureIgnoreCase) && value is string cultureCode) + if (columnName.Equals(nameof(ActivityInfo.ActivityLanguageID), StringComparison.InvariantCultureIgnoreCase) && value is string cultureCode) { return ValueInterceptorResult.ReplaceValue(ContentLanguageInfoProvider.ProviderObject.Get(cultureCode)?.ContentLanguageID); } From c7adf665578c37f91c321e478cfabc4482f6c694 Mon Sep 17 00:00:00 2001 From: akfakmot Date: Wed, 13 Nov 2024 12:24:55 +0100 Subject: [PATCH 2/4] Remove KXP dependency from K11 MigrateDataProtectionCommandHandler Refactor: Remove KXP dependency from K11 MigrateDataProtectionCommandHandler --- .../MigrateDataProtectionCommandHandler.cs | 189 ++++-------------- .../K11CoreDiExtensions.cs | 7 +- .../Mappers/CmsConsentAgreementMapper.cs | 13 +- .../Mappers/CmsConsentArchiveMapper.cs | 9 +- .../Mappers/CmsConsentMapper.cs | 9 +- 5 files changed, 56 insertions(+), 171 deletions(-) diff --git a/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs b/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs index f8a82f84..4e107eed 100644 --- a/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs +++ b/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs @@ -1,3 +1,5 @@ +using CMS.ContactManagement; +using CMS.DataEngine; using CMS.DataProtection; using MediatR; @@ -16,43 +18,17 @@ namespace Migration.Tool.Core.K11.Handlers; -public class MigrateDataProtectionCommandHandler : IRequestHandler, IDisposable +public class MigrateDataProtectionCommandHandler( + ILogger logger, + IDbContextFactory k11ContextFactory, + IEntityMapper consentAgreementMapper, + IEntityMapper consentArchiveMapper, + IEntityMapper consentMapper, + PrimaryKeyMappingContext primaryKeyMappingContext, + IProtocol protocol + ) : IRequestHandler { private static readonly int batchSize = 1000; - private readonly IEntityMapper consentAgreementMapper; - private readonly IEntityMapper consentArchiveMapper; - private readonly IEntityMapper consentMapper; - private readonly IDbContextFactory k11ContextFactory; - private readonly IDbContextFactory kxpContextFactory; - private readonly ILogger logger; - private readonly PrimaryKeyMappingContext primaryKeyMappingContext; - private readonly IProtocol protocol; - - private KxpContext kxpContext; - - public MigrateDataProtectionCommandHandler( - ILogger logger, - IDbContextFactory kxpContextFactory, - IDbContextFactory k11ContextFactory, - IEntityMapper consentMapper, - IEntityMapper consentArchiveMapper, - IEntityMapper consentAgreementMapper, - PrimaryKeyMappingContext primaryKeyMappingContext, - IProtocol protocol - ) - { - this.logger = logger; - this.kxpContextFactory = kxpContextFactory; - this.k11ContextFactory = k11ContextFactory; - this.consentMapper = consentMapper; - this.consentArchiveMapper = consentArchiveMapper; - this.consentAgreementMapper = consentAgreementMapper; - this.primaryKeyMappingContext = primaryKeyMappingContext; - this.protocol = protocol; - kxpContext = this.kxpContextFactory.CreateDbContext(); - } - - public void Dispose() => kxpContext.Dispose(); public async Task Handle(MigrateDataProtectionCommand request, CancellationToken cancellationToken) { @@ -72,7 +48,7 @@ private async Task MigrateConsent(CancellationToken cancellationT protocol.FetchedSource(k11Consent); logger.LogTrace("Migrating consent {ConsentName} with ConsentGuid {ConsentGuid}", k11Consent.ConsentName, k11Consent.ConsentGuid); - var kxoConsent = await kxpContext.CmsConsents.FirstOrDefaultAsync(consent => consent.ConsentGuid == k11Consent.ConsentGuid, cancellationToken); + var kxoConsent = ConsentInfo.Provider.Get().WhereEquals(nameof(ConsentInfo.ConsentGuid), k11Consent.ConsentGuid).FirstOrDefault(); protocol.FetchedTarget(kxoConsent); var mapped = consentMapper.Map(k11Consent, kxoConsent); @@ -80,38 +56,13 @@ private async Task MigrateConsent(CancellationToken cancellationT if (mapped is { Success: true } result) { - (var cmsConsent, bool newInstance) = result; - ArgumentNullException.ThrowIfNull(cmsConsent, nameof(cmsConsent)); - - if (newInstance) - { - kxpContext.CmsConsents.Add(cmsConsent); - } - else - { - kxpContext.CmsConsents.Update(cmsConsent); - } + (var consentInfo, bool newInstance) = result; + ArgumentNullException.ThrowIfNull(consentInfo, nameof(consentInfo)); - try - { - await kxpContext.SaveChangesAsync(cancellationToken); - - protocol.Success(k11Consent, cmsConsent, mapped); - logger.LogEntitySetAction(newInstance, cmsConsent); - primaryKeyMappingContext.SetMapping(r => r.ConsentId, k11Consent.ConsentId, cmsConsent.ConsentId); - } - /*Violation in unique index or Violation in unique constraint */ - catch (DbUpdateException dbUpdateException) when (dbUpdateException.InnerException is SqlException { Number: 2601 or 2627 } sqlException) - { - logger.LogEntitySetError(sqlException, newInstance, k11Consent); - protocol.Append(HandbookReferences - .DbConstraintBroken(sqlException, k11Consent) - .WithMessage("Failed to migrate consent, target database constraint broken.") - ); - - await kxpContext.DisposeAsync(); - kxpContext = await kxpContextFactory.CreateDbContextAsync(cancellationToken); - } + ConsentInfo.Provider.Set(consentInfo); + protocol.Success(k11Consent, consentInfo, mapped); + logger.LogEntitySetAction(newInstance, consentInfo); + primaryKeyMappingContext.SetMapping(r => r.ConsentId, k11Consent.ConsentId, consentInfo.ConsentID); } } @@ -127,7 +78,7 @@ private async Task MigrateConsentArchive(CancellationToken cancel protocol.FetchedSource(k11ArchiveConsent); logger.LogTrace("Migrating consent archive with ConsentArchiveGuid {ConsentGuid}", k11ArchiveConsent.ConsentArchiveGuid); - var kxoConsentArchive = await kxpContext.CmsConsentArchives.FirstOrDefaultAsync(consentArchive => consentArchive.ConsentArchiveGuid == k11ArchiveConsent.ConsentArchiveGuid, cancellationToken); + var kxoConsentArchive = ConsentArchiveInfo.Provider.Get().WhereEquals(nameof(ConsentArchiveInfo.ConsentArchiveGuid), k11ArchiveConsent.ConsentArchiveGuid).FirstOrDefault(); protocol.FetchedTarget(kxoConsentArchive); var mapped = consentArchiveMapper.Map(k11ArchiveConsent, kxoConsentArchive); @@ -135,39 +86,14 @@ private async Task MigrateConsentArchive(CancellationToken cancel if (mapped is { Success: true } result) { - (var cmsConsentArchive, bool newInstance) = result; - ArgumentNullException.ThrowIfNull(cmsConsentArchive, nameof(cmsConsentArchive)); - - if (newInstance) - { - kxpContext.CmsConsentArchives.Add(cmsConsentArchive); - } - else - { - kxpContext.CmsConsentArchives.Update(cmsConsentArchive); - } - - try - { - await kxpContext.SaveChangesAsync(cancellationToken); - - protocol.Success(k11ArchiveConsent, cmsConsentArchive, mapped); - logger.LogEntitySetAction(newInstance, cmsConsentArchive); - primaryKeyMappingContext.SetMapping(r => r.ConsentArchiveGuid, - k11ArchiveConsent.ConsentArchiveId, cmsConsentArchive.ConsentArchiveId); - } - /*Violation in unique index or Violation in unique constraint */ - catch (DbUpdateException dbUpdateException) when (dbUpdateException.InnerException is SqlException { Number: 2601 or 2627 } sqlException) - { - logger.LogEntitySetError(sqlException, newInstance, k11ArchiveConsent); - protocol.Append(HandbookReferences - .DbConstraintBroken(sqlException, k11ArchiveConsent) - .WithMessage("Failed to migrate consent archive, target database constraint broken.") - ); - - await kxpContext.DisposeAsync(); - kxpContext = await kxpContextFactory.CreateDbContextAsync(cancellationToken); - } + (var consentArchiveInfo, bool newInstance) = result; + ArgumentNullException.ThrowIfNull(consentArchiveInfo, nameof(consentArchiveInfo)); + + ConsentArchiveInfo.Provider.Set(consentArchiveInfo); + protocol.Success(k11ArchiveConsent, consentArchiveInfo, mapped); + logger.LogEntitySetAction(newInstance, consentArchiveInfo); + primaryKeyMappingContext.SetMapping(r => r.ConsentArchiveGuid, + k11ArchiveConsent.ConsentArchiveId, consentArchiveInfo.ConsentArchiveID); } } @@ -179,8 +105,8 @@ private async Task MigrateConsentAgreement(CancellationToken canc await using var k11Context = await k11ContextFactory.CreateDbContextAsync(cancellationToken); int index = 0; int indexFull = 0; - var consentAgreementUpdates = new List(); - var consentAgreementNews = new List(); + var consentAgreementUpdates = new List(); + var consentAgreementNews = new List(); int itemsCount = k11Context.CmsConsentAgreements.Count(); foreach (var k11ConsentAgreement in k11Context.CmsConsentAgreements) @@ -188,7 +114,7 @@ private async Task MigrateConsentAgreement(CancellationToken canc protocol.FetchedSource(k11ConsentAgreement); logger.LogTrace("Migrating consent agreement with ConsentAgreementGuid {ConsentAgreementGuid}", k11ConsentAgreement.ConsentAgreementGuid); - var kxoConsentAgreement = await kxpContext.CmsConsentAgreements.FirstOrDefaultAsync(consentAgreement => consentAgreement.ConsentAgreementGuid == k11ConsentAgreement.ConsentAgreementGuid, cancellationToken); + var kxoConsentAgreement = ConsentAgreementInfo.Provider.Get().WhereEquals(nameof(ConsentAgreementInfo.ConsentAgreementGuid), k11ConsentAgreement.ConsentAgreementGuid).FirstOrDefault(); protocol.FetchedTarget(kxoConsentAgreement); var mapped = consentAgreementMapper.Map(k11ConsentAgreement, kxoConsentAgreement); @@ -196,16 +122,16 @@ private async Task MigrateConsentAgreement(CancellationToken canc if (mapped is { Success: true } result) { - (var cmsConsentAgreement, bool newInstance) = result; - ArgumentNullException.ThrowIfNull(cmsConsentAgreement, nameof(cmsConsentAgreement)); - + (var agreementInfo, bool newInstance) = result; + ArgumentNullException.ThrowIfNull(agreementInfo, nameof(agreementInfo)); + if (newInstance) { - consentAgreementNews.Add(cmsConsentAgreement); + consentAgreementNews.Add(agreementInfo); } else { - consentAgreementUpdates.Add(cmsConsentAgreement); + ConsentAgreementInfo.Provider.Set(agreementInfo); } } @@ -214,58 +140,15 @@ private async Task MigrateConsentAgreement(CancellationToken canc if (index == batchSize || indexFull == itemsCount) { - kxpContext.CmsConsentAgreements.AddRange(consentAgreementNews); - kxpContext.CmsConsentAgreements.UpdateRange(consentAgreementUpdates); - try { - await kxpContext.SaveChangesAsync(cancellationToken); - + ConsentAgreementInfo.Provider.BulkInsert(consentAgreementNews); foreach (var newK11ConsentAgreement in consentAgreementNews) { protocol.Success(k11ConsentAgreement, newK11ConsentAgreement, mapped); logger.LogDebug("CmsConsentAgreement: with ConsentAgreementGuid \'{ConsentAgreementGuid}\' was inserted", newK11ConsentAgreement.ConsentAgreementGuid); } - - foreach (var updateK11ConsentAgreement in consentAgreementUpdates) - { - protocol.Success(k11ConsentAgreement, updateK11ConsentAgreement, mapped); - logger.LogDebug("CmsConsentAgreement: with ConsentAgreementGuid \'{ConsentAgreementGuid}\' was updated", - updateK11ConsentAgreement.ConsentAgreementGuid); - } - } - catch (DbUpdateException dbUpdateException) when ( - dbUpdateException.InnerException is SqlException sqlException && - sqlException.Message.Contains("Cannot insert duplicate key row in object") - ) - { - await kxpContext.DisposeAsync(); - - protocol.Append(HandbookReferences - .ErrorCreatingTargetInstance(dbUpdateException) - .NeedsManualAction() - .WithIdentityPrints(consentAgreementNews) - ); - logger.LogEntitiesSetError(dbUpdateException, true, consentAgreementNews); - - - protocol.Append(HandbookReferences - .ErrorUpdatingTargetInstance(dbUpdateException) - .NeedsManualAction() - .WithIdentityPrints(consentAgreementUpdates) - ); - - var cai = ConsentAgreementInfo.New(); - protocol.Append(HandbookReferences - .ErrorUpdatingTargetInstance(dbUpdateException) - .NeedsManualAction() - .WithIdentityPrint(cai) - ); - - logger.LogEntitiesSetError(dbUpdateException, false, consentAgreementUpdates); - - kxpContext = await kxpContextFactory.CreateDbContextAsync(cancellationToken); } finally { diff --git a/Migration.Tool.Core.K11/K11CoreDiExtensions.cs b/Migration.Tool.Core.K11/K11CoreDiExtensions.cs index 08bf7db8..987cdb80 100644 --- a/Migration.Tool.Core.K11/K11CoreDiExtensions.cs +++ b/Migration.Tool.Core.K11/K11CoreDiExtensions.cs @@ -1,4 +1,5 @@ using CMS.DataEngine; +using CMS.DataProtection; using CMS.FormEngine; using CMS.Globalization; using CMS.MediaLibrary; @@ -47,9 +48,9 @@ public static IServiceCollection UseK11ToolCore(this IServiceCollection services // mappers services.AddTransient, CmsAttachmentMapper>(); - services.AddTransient, CmsConsentMapper>(); - services.AddTransient, CmsConsentAgreementMapper>(); - services.AddTransient, CmsConsentArchiveMapper>(); + services.AddTransient, CmsConsentMapper>(); + services.AddTransient, CmsConsentAgreementMapper>(); + services.AddTransient, CmsConsentArchiveMapper>(); services.AddTransient, AlternativeFormMapper>(); services.AddTransient, RoleInfoMapper>(); services.AddTransient, CmsSettingsCategoryMapper>(); diff --git a/Migration.Tool.Core.K11/Mappers/CmsConsentAgreementMapper.cs b/Migration.Tool.Core.K11/Mappers/CmsConsentAgreementMapper.cs index ba95658c..94cbdbcc 100644 --- a/Migration.Tool.Core.K11/Mappers/CmsConsentAgreementMapper.cs +++ b/Migration.Tool.Core.K11/Mappers/CmsConsentAgreementMapper.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.Logging; +using CMS.DataProtection; +using Microsoft.Extensions.Logging; using Migration.Tool.Common.Abstractions; using Migration.Tool.Common.MigrationProtocol; @@ -8,11 +9,11 @@ namespace Migration.Tool.Core.K11.Mappers; public class CmsConsentAgreementMapper(ILogger logger, PrimaryKeyMappingContext primaryKeyMappingContext, IProtocol protocol) - : EntityMapperBase(logger, primaryKeyMappingContext, protocol) + : EntityMapperBase(logger, primaryKeyMappingContext, protocol) { - protected override KXP.Models.CmsConsentAgreement? CreateNewInstance(CmsConsentAgreement source, MappingHelper mappingHelper, AddFailure addFailure) => new(); + protected override ConsentAgreementInfo? CreateNewInstance(CmsConsentAgreement source, MappingHelper mappingHelper, AddFailure addFailure) => new(); - protected override KXP.Models.CmsConsentAgreement MapInternal(CmsConsentAgreement source, KXP.Models.CmsConsentAgreement target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) + protected override ConsentAgreementInfo MapInternal(CmsConsentAgreement source, ConsentAgreementInfo target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) { target.ConsentAgreementGuid = source.ConsentAgreementGuid; target.ConsentAgreementRevoked = source.ConsentAgreementRevoked; @@ -21,12 +22,12 @@ protected override KXP.Models.CmsConsentAgreement MapInternal(CmsConsentAgreemen if (mappingHelper.TranslateRequiredId(c => c.ContactId, source.ConsentAgreementContactId, out int contactId)) { - target.ConsentAgreementContactId = contactId; + target.ConsentAgreementContactID = contactId; } if (mappingHelper.TranslateRequiredId(r => r.ConsentId, source.ConsentAgreementConsentId, out int consentId)) { - target.ConsentAgreementConsentId = consentId; + target.ConsentAgreementConsentID = consentId; } return target; diff --git a/Migration.Tool.Core.K11/Mappers/CmsConsentArchiveMapper.cs b/Migration.Tool.Core.K11/Mappers/CmsConsentArchiveMapper.cs index 3e651447..6d771460 100644 --- a/Migration.Tool.Core.K11/Mappers/CmsConsentArchiveMapper.cs +++ b/Migration.Tool.Core.K11/Mappers/CmsConsentArchiveMapper.cs @@ -1,3 +1,4 @@ +using CMS.DataProtection; using Microsoft.Extensions.Logging; using Migration.Tool.Common.Abstractions; @@ -11,11 +12,11 @@ public class CmsConsentArchiveMapper( ILogger logger, PrimaryKeyMappingContext primaryKeyMappingContext, IProtocol protocol) - : EntityMapperBase(logger, primaryKeyMappingContext, protocol) + : EntityMapperBase(logger, primaryKeyMappingContext, protocol) { - protected override KXP.Models.CmsConsentArchive? CreateNewInstance(CmsConsentArchive source, MappingHelper mappingHelper, AddFailure addFailure) => new(); + protected override ConsentArchiveInfo? CreateNewInstance(CmsConsentArchive source, MappingHelper mappingHelper, AddFailure addFailure) => new(); - protected override KXP.Models.CmsConsentArchive MapInternal(CmsConsentArchive source, KXP.Models.CmsConsentArchive target, bool newInstance, + protected override ConsentArchiveInfo MapInternal(CmsConsentArchive source, ConsentArchiveInfo target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) { target.ConsentArchiveContent = source.ConsentArchiveContent; @@ -25,7 +26,7 @@ protected override KXP.Models.CmsConsentArchive MapInternal(CmsConsentArchive so if (mappingHelper.TranslateRequiredId(r => r.ConsentId, source.ConsentArchiveConsentId, out int consentId)) { - target.ConsentArchiveConsentId = consentId; + target.ConsentArchiveConsentID = consentId; } return target; diff --git a/Migration.Tool.Core.K11/Mappers/CmsConsentMapper.cs b/Migration.Tool.Core.K11/Mappers/CmsConsentMapper.cs index b6fa5e1f..1e138cdd 100644 --- a/Migration.Tool.Core.K11/Mappers/CmsConsentMapper.cs +++ b/Migration.Tool.Core.K11/Mappers/CmsConsentMapper.cs @@ -3,7 +3,7 @@ using System.Xml.XPath; using CMS.ContentEngine; - +using CMS.DataProtection; using Microsoft.Extensions.Logging; using Migration.Tool.Common.Abstractions; @@ -13,11 +13,11 @@ namespace Migration.Tool.Core.K11.Mappers; -public class CmsConsentMapper(ILogger logger, PrimaryKeyMappingContext pkContext, IProtocol protocol) : EntityMapperBase(logger, pkContext, protocol) +public class CmsConsentMapper(ILogger logger, PrimaryKeyMappingContext pkContext, IProtocol protocol) : EntityMapperBase(logger, pkContext, protocol) { - protected override KXP.Models.CmsConsent? CreateNewInstance(CmsConsent source, MappingHelper mappingHelper, AddFailure addFailure) => new(); + protected override ConsentInfo? CreateNewInstance(CmsConsent source, MappingHelper mappingHelper, AddFailure addFailure) => new(); - protected override KXP.Models.CmsConsent MapInternal(CmsConsent source, KXP.Models.CmsConsent target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) + protected override ConsentInfo MapInternal(CmsConsent source, ConsentInfo target, bool newInstance, MappingHelper mappingHelper, AddFailure addFailure) { target.ConsentDisplayName = source.ConsentDisplayName; var defaultContentLanguageInfo = ContentLanguageInfo.Provider.Get().WhereEquals(nameof(ContentLanguageInfo.ContentLanguageIsDefault), true).FirstOrDefault() ?? throw new InvalidCastException("Missing default content language"); @@ -25,7 +25,6 @@ protected override KXP.Models.CmsConsent MapInternal(CmsConsent source, KXP.Mode target.ConsentContent = ConsentContentPatcher.PatchConsentContent(source.ConsentContent, defaultContentLanguageInfo); target.ConsentGuid = source.ConsentGuid; target.ConsentLastModified = source.ConsentLastModified; - target.ConsentHash = source.ConsentHash; return target; } From 26c142d28cf93ee4ae17e9c5cd19694db79963c0 Mon Sep 17 00:00:00 2001 From: akfakmot Date: Wed, 13 Nov 2024 16:47:20 +0100 Subject: [PATCH 3/4] 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; } } From 5ea5fb59a1e3de8acb9fd37efbea16254986394c Mon Sep 17 00:00:00 2001 From: akfakmot Date: Wed, 13 Nov 2024 17:39:13 +0100 Subject: [PATCH 4/4] Fix formatting Chore: Fix formatting --- .../Handlers/MigrateDataProtectionCommandHandler.cs | 2 +- Migration.Tool.Core.K11/Mappers/OmContactGroupMapper.cs | 2 +- Migration.Tool.Core.K11/Services/KeyLocatorService.cs | 2 -- Migration.Tool.Core.K11/Services/PrimaryKeyLocatorService.cs | 1 - 4 files changed, 2 insertions(+), 5 deletions(-) diff --git a/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs b/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs index eec8aead..4b8ab216 100644 --- a/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs +++ b/Migration.Tool.Core.K11/Handlers/MigrateDataProtectionCommandHandler.cs @@ -121,7 +121,7 @@ private async Task MigrateConsentAgreement(CancellationToken canc { (var agreementInfo, bool newInstance) = result; ArgumentNullException.ThrowIfNull(agreementInfo, nameof(agreementInfo)); - + if (newInstance) { consentAgreementNews.Add(agreementInfo); diff --git a/Migration.Tool.Core.K11/Mappers/OmContactGroupMapper.cs b/Migration.Tool.Core.K11/Mappers/OmContactGroupMapper.cs index d2d986d5..90b7432f 100644 --- a/Migration.Tool.Core.K11/Mappers/OmContactGroupMapper.cs +++ b/Migration.Tool.Core.K11/Mappers/OmContactGroupMapper.cs @@ -19,7 +19,7 @@ public class OmContactGroupMapper( 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 + T RequireValue(string propertyName, T? value, T defaultValue) where T : struct { if (value.HasValue) { diff --git a/Migration.Tool.Core.K11/Services/KeyLocatorService.cs b/Migration.Tool.Core.K11/Services/KeyLocatorService.cs index 533e6a51..7b535157 100644 --- a/Migration.Tool.Core.K11/Services/KeyLocatorService.cs +++ b/Migration.Tool.Core.K11/Services/KeyLocatorService.cs @@ -1,7 +1,5 @@ using System.Linq.Expressions; using System.Runtime.CompilerServices; -using CMS.ContactManagement; -using CMS.DataEngine; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; diff --git a/Migration.Tool.Core.K11/Services/PrimaryKeyLocatorService.cs b/Migration.Tool.Core.K11/Services/PrimaryKeyLocatorService.cs index bdc8516d..3acb83a6 100644 --- a/Migration.Tool.Core.K11/Services/PrimaryKeyLocatorService.cs +++ b/Migration.Tool.Core.K11/Services/PrimaryKeyLocatorService.cs @@ -5,7 +5,6 @@ using CMS.Globalization; using CMS.Membership; using CMS.Modules; -using CMS.OnlineForms; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging;