diff --git a/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs b/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs index de2ae97a2df8..1ce0d361cd02 100644 --- a/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs +++ b/src/Umbraco.Cms.Api.Management/Controllers/Security/BackOfficeController.cs @@ -254,7 +254,7 @@ public async Task Token() if (associatedUser is not null) { // log current datetime as last login (this also ensures that the user is not flagged as inactive) - associatedUser.LastLoginDateUtc = DateTime.UtcNow; + associatedUser.LastLoginDate = DateTime.UtcNow; await _backOfficeUserManager.UpdateAsync(associatedUser); return await SignInBackOfficeUser(associatedUser, request); diff --git a/src/Umbraco.Cms.Persistence.SqlServer/Services/SqlServerSyntaxProvider.cs b/src/Umbraco.Cms.Persistence.SqlServer/Services/SqlServerSyntaxProvider.cs index 87d736ac3453..28ff4806a426 100644 --- a/src/Umbraco.Cms.Persistence.SqlServer/Services/SqlServerSyntaxProvider.cs +++ b/src/Umbraco.Cms.Persistence.SqlServer/Services/SqlServerSyntaxProvider.cs @@ -312,11 +312,8 @@ protected override string FormatIdentity(ColumnDefinition column) => return "NEWID()"; case SystemMethods.CurrentDateTime: return "GETDATE()"; - - // case SystemMethods.NewSequentialId: - // return "NEWSEQUENTIALID()"; - // case SystemMethods.CurrentUTCDateTime: - // return "GETUTCDATE()"; + case SystemMethods.CurrentUTCDateTime: + return "GETUTCDATE()"; } return null; diff --git a/src/Umbraco.Cms.Persistence.Sqlite/Services/SqliteSyntaxProvider.cs b/src/Umbraco.Cms.Persistence.Sqlite/Services/SqliteSyntaxProvider.cs index 2ed07cbf026d..0ec26f11374f 100644 --- a/src/Umbraco.Cms.Persistence.Sqlite/Services/SqliteSyntaxProvider.cs +++ b/src/Umbraco.Cms.Persistence.Sqlite/Services/SqliteSyntaxProvider.cs @@ -203,13 +203,14 @@ private static string GetColumnName(PropertyInfo column) /// protected override string? FormatSystemMethods(SystemMethods systemMethod) { - // TODO: SQLite switch (systemMethod) { case SystemMethods.NewGuid: - return "NEWID()"; // No NEWID() in SQLite perhaps try RANDOM() + return null; // Not available in SQLite. case SystemMethods.CurrentDateTime: - return "DATE()"; // No GETDATE() trying DATE() + return null; // Not available in SQLite. + case SystemMethods.CurrentUTCDateTime: + return "CURRENT_TIMESTAMP"; } return null; diff --git a/src/Umbraco.Core/Configuration/Models/SystemDateMigrationSettings.cs b/src/Umbraco.Core/Configuration/Models/SystemDateMigrationSettings.cs new file mode 100644 index 000000000000..231911b89a9f --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/SystemDateMigrationSettings.cs @@ -0,0 +1,28 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using System.ComponentModel; + +namespace Umbraco.Cms.Core.Configuration.Models; + +/// +/// Typed configuration options used for migration of system dates to UTC from a Umbraco 16 or lower solution. +/// +[UmbracoOptions(Constants.Configuration.ConfigSystemDateMigration)] +public class SystemDateMigrationSettings +{ + private const bool StaticEnabled = true; + + /// + /// Gets or sets a value indicating whether the migration is enabled. + /// + [DefaultValue(StaticEnabled)] + public bool Enabled { get; set; } = StaticEnabled; + + /// + /// Gets or sets the local server timezone standard name. + /// If not provided, the local server time zone is detected. + /// + [DefaultValue(null)] + public string? LocalServerTimeZone { get; set; } +} diff --git a/src/Umbraco.Core/Configuration/Models/Validation/SystemDateMigrationSettingsValidator.cs b/src/Umbraco.Core/Configuration/Models/Validation/SystemDateMigrationSettingsValidator.cs new file mode 100644 index 000000000000..a4686663d7f6 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/Validation/SystemDateMigrationSettingsValidator.cs @@ -0,0 +1,30 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.Extensions.Options; + +namespace Umbraco.Cms.Core.Configuration.Models.Validation; + +/// +/// Validator for configuration representated as . +/// +public class SystemDateMigrationSettingsValidator + : IValidateOptions +{ + /// + public ValidateOptionsResult Validate(string? name, SystemDateMigrationSettings options) + { + if (string.IsNullOrWhiteSpace(options.LocalServerTimeZone)) + { + return ValidateOptionsResult.Success; + } + + if (TimeZoneInfo.TryFindSystemTimeZoneById(options.LocalServerTimeZone, out _) is false) + { + return ValidateOptionsResult.Fail( + $"Configuration entry {Constants.Configuration.ConfigSystemDateMigration} contains an invalid time zone: {options.LocalServerTimeZone}."); + } + + return ValidateOptionsResult.Success; + } +} diff --git a/src/Umbraco.Core/Constants-Configuration.cs b/src/Umbraco.Core/Constants-Configuration.cs index 8504210504d8..10f8e6f8cc3e 100644 --- a/src/Umbraco.Core/Constants-Configuration.cs +++ b/src/Umbraco.Core/Constants-Configuration.cs @@ -28,6 +28,7 @@ public static class Configuration public const string ConfigActiveDirectory = ConfigPrefix + "ActiveDirectory"; public const string ConfigMarketplace = ConfigPrefix + "Marketplace"; public const string ConfigLegacyPasswordMigration = ConfigPrefix + "LegacyPasswordMigration"; + public const string ConfigSystemDateMigration = ConfigPrefix + "SystemDateMigration"; public const string ConfigContent = ConfigPrefix + "Content"; public const string ConfigDeliveryApi = ConfigPrefix + "DeliveryApi"; public const string ConfigCoreDebug = ConfigCorePrefix + "Debug"; diff --git a/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.Configuration.cs b/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.Configuration.cs index cc9b03e65b7d..52d136e75326 100644 --- a/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.Configuration.cs +++ b/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.Configuration.cs @@ -47,6 +47,7 @@ public static IUmbracoBuilder AddConfiguration(this IUmbracoBuilder builder) builder.Services.AddSingleton, RequestHandlerSettingsValidator>(); builder.Services.AddSingleton, UnattendedSettingsValidator>(); builder.Services.AddSingleton, SecuritySettingsValidator>(); + builder.Services.AddSingleton, SystemDateMigrationSettingsValidator>(); // Register configuration sections. builder @@ -86,7 +87,8 @@ public static IUmbracoBuilder AddConfiguration(this IUmbracoBuilder builder) .AddUmbracoOptions() .AddUmbracoOptions() .AddUmbracoOptions() - .AddUmbracoOptions(); + .AddUmbracoOptions() + .AddUmbracoOptions(); // Configure connection string and ensure it's updated when the configuration changes builder.Services.AddSingleton, ConfigureConnectionStrings>(); diff --git a/src/Umbraco.Core/Extensions/EntityFactoryDateTimeExtensions.cs b/src/Umbraco.Core/Extensions/EntityFactoryDateTimeExtensions.cs new file mode 100644 index 000000000000..d7fcedf84ea6 --- /dev/null +++ b/src/Umbraco.Core/Extensions/EntityFactoryDateTimeExtensions.cs @@ -0,0 +1,30 @@ +namespace Umbraco.Cms.Core.Extensions; + +/// +/// Provides extensions on purely when building entities from persistence DTOs. +/// +public static class EntityFactoryDateTimeExtensions +{ + /// + /// Ensures the provided DateTime is in UTC format. + /// + /// + /// We need this in the particular cases of building entities from persistence DTOs. NPoco isn't consistent in what it returns + /// here across databases, sometimes providing a Kind of Unspecified. We are consistently persisting UTC for Umbraco's system + /// dates so we should enforce this Kind on the entity before exposing it further within the Umbraco application. + /// + public static DateTime EnsureUtc(this DateTime dateTime) + { + if (dateTime.Kind == DateTimeKind.Utc) + { + return dateTime; + } + + if (dateTime.Kind == DateTimeKind.Local) + { + return dateTime.ToUniversalTime(); + } + + return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); + } +} diff --git a/src/Umbraco.Core/Models/AuditEntry.cs b/src/Umbraco.Core/Models/AuditEntry.cs index 2d621e93f428..33ab9d8f9f30 100644 --- a/src/Umbraco.Core/Models/AuditEntry.cs +++ b/src/Umbraco.Core/Models/AuditEntry.cs @@ -49,7 +49,7 @@ public string? PerformingIp } /// - public DateTime EventDateUtc + public DateTime EventDate { get => CreateDate; set => CreateDate = value; diff --git a/src/Umbraco.Core/Models/ContentBase.cs b/src/Umbraco.Core/Models/ContentBase.cs index f9fa7263ba29..2bb9c1543fce 100644 --- a/src/Umbraco.Core/Models/ContentBase.cs +++ b/src/Umbraco.Core/Models/ContentBase.cs @@ -307,7 +307,7 @@ public void SetCultureName(string? name, string? culture) // set else if (GetCultureName(culture) != name) { - this.SetCultureInfo(culture!, name, DateTime.Now); + this.SetCultureInfo(culture!, name, DateTime.UtcNow); } } diff --git a/src/Umbraco.Core/Models/ContentRepositoryExtensions.cs b/src/Umbraco.Core/Models/ContentRepositoryExtensions.cs index c922cea2b35d..c8663e18b154 100644 --- a/src/Umbraco.Core/Models/ContentRepositoryExtensions.cs +++ b/src/Umbraco.Core/Models/ContentRepositoryExtensions.cs @@ -52,7 +52,7 @@ public static void TouchCulture(this IContentBase content, string? culture) return; } - content.CultureInfos?.AddOrUpdate(culture!, infos.Name, DateTime.Now); + content.CultureInfos?.AddOrUpdate(culture!, infos.Name, DateTime.UtcNow); } /// diff --git a/src/Umbraco.Core/Models/ContentVersionMeta.cs b/src/Umbraco.Core/Models/ContentVersionMeta.cs index b9b1be60801e..768f16c71d49 100644 --- a/src/Umbraco.Core/Models/ContentVersionMeta.cs +++ b/src/Umbraco.Core/Models/ContentVersionMeta.cs @@ -1,3 +1,5 @@ +using Umbraco.Cms.Core.Extensions; + namespace Umbraco.Cms.Core.Models; public class ContentVersionMeta @@ -47,7 +49,7 @@ public ContentVersionMeta( public string? Username { get; } - public void SpecifyVersionDateKind(DateTimeKind kind) => VersionDate = DateTime.SpecifyKind(VersionDate, kind); - public override string ToString() => $"ContentVersionMeta(versionId: {VersionId}, versionDate: {VersionDate:s}"; + + public void EnsureUtc() => VersionDate = VersionDate.EnsureUtc(); } diff --git a/src/Umbraco.Core/Models/Entities/EntityExtensions.cs b/src/Umbraco.Core/Models/Entities/EntityExtensions.cs index 53801875aebe..2fe26b78fbe3 100644 --- a/src/Umbraco.Core/Models/Entities/EntityExtensions.cs +++ b/src/Umbraco.Core/Models/Entities/EntityExtensions.cs @@ -12,7 +12,7 @@ public static class EntityExtensions /// public static void UpdatingEntity(this IEntity entity) { - DateTime now = DateTime.Now; + DateTime now = DateTime.UtcNow; if (entity.CreateDate == default) { @@ -32,7 +32,7 @@ public static void UpdatingEntity(this IEntity entity) /// public static void AddingEntity(this IEntity entity) { - DateTime now = DateTime.Now; + DateTime now = DateTime.UtcNow; var canBeDirty = entity as ICanBeDirty; // set the create and update dates, if not already set diff --git a/src/Umbraco.Core/Models/IAuditEntry.cs b/src/Umbraco.Core/Models/IAuditEntry.cs index e01f979fbfd6..8b8111173458 100644 --- a/src/Umbraco.Core/Models/IAuditEntry.cs +++ b/src/Umbraco.Core/Models/IAuditEntry.cs @@ -46,7 +46,7 @@ public interface IAuditEntry : IEntity, IRememberBeingDirty /// /// Gets or sets the date and time of the audited event. /// - DateTime EventDateUtc { get; set; } + DateTime EventDate { get; set; } /// /// Gets or sets the identifier of the user affected by the audited event. diff --git a/src/Umbraco.Core/Models/ReadOnlyRelation.cs b/src/Umbraco.Core/Models/ReadOnlyRelation.cs index 4388499e98de..8729dd50f5b3 100644 --- a/src/Umbraco.Core/Models/ReadOnlyRelation.cs +++ b/src/Umbraco.Core/Models/ReadOnlyRelation.cs @@ -17,7 +17,7 @@ public ReadOnlyRelation(int id, int parentId, int childId, int relationTypeId, D } public ReadOnlyRelation(int parentId, int childId, int relationTypeId) - : this(0, parentId, childId, relationTypeId, DateTime.Now, string.Empty) + : this(0, parentId, childId, relationTypeId, DateTime.UtcNow, string.Empty) { } diff --git a/src/Umbraco.Core/PublishedCache/Internal/InternalPublishedContent.cs b/src/Umbraco.Core/PublishedCache/Internal/InternalPublishedContent.cs index 90c407075287..df0975115578 100644 --- a/src/Umbraco.Core/PublishedCache/Internal/InternalPublishedContent.cs +++ b/src/Umbraco.Core/PublishedCache/Internal/InternalPublishedContent.cs @@ -18,7 +18,7 @@ public InternalPublishedContent(IPublishedContentType contentType) // initialize boring stuff TemplateId = 0; WriterId = CreatorId = 0; - CreateDate = UpdateDate = DateTime.Now; + CreateDate = UpdateDate = DateTime.UtcNow; Version = Guid.Empty; Path = string.Empty; ContentType = contentType; diff --git a/src/Umbraco.Core/Services/AuditEntryService.cs b/src/Umbraco.Core/Services/AuditEntryService.cs index e1743858b014..8cc8d5441dc3 100644 --- a/src/Umbraco.Core/Services/AuditEntryService.cs +++ b/src/Umbraco.Core/Services/AuditEntryService.cs @@ -143,7 +143,7 @@ private IAuditEntry WriteInner( PerformingUserKey = performingUserKey, PerformingDetails = performingDetails, PerformingIp = performingIp, - EventDateUtc = eventDateUtc, + EventDate = eventDateUtc, AffectedUserId = affectedUserId ?? Constants.Security.UnknownUserId, // Default to UnknownUserId as it is non-nullable AffectedUserKey = affectedUserKey, AffectedDetails = affectedDetails, diff --git a/src/Umbraco.Core/Services/ConsentService.cs b/src/Umbraco.Core/Services/ConsentService.cs index 40b76f5a8ef2..a688f55ff1f8 100644 --- a/src/Umbraco.Core/Services/ConsentService.cs +++ b/src/Umbraco.Core/Services/ConsentService.cs @@ -52,7 +52,7 @@ public IConsent RegisterConsent(string source, string context, string action, Co Source = source, Context = context, Action = action, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, State = state, Comment = comment, }; diff --git a/src/Umbraco.Core/Services/ContentService.cs b/src/Umbraco.Core/Services/ContentService.cs index 246682ec14da..6bf9ddbbfa43 100644 --- a/src/Umbraco.Core/Services/ContentService.cs +++ b/src/Umbraco.Core/Services/ContentService.cs @@ -1248,7 +1248,7 @@ public PublishResult Publish(IContent content, string[] cultures, int userId = C // publish the culture(s) // we don't care about the response here, this response will be rechecked below but we need to set the culture info values now. - var publishTime = DateTime.Now; + var publishTime = DateTime.UtcNow; foreach (CultureImpact? impact in impacts) { content.PublishCulture(impact, publishTime, _propertyEditorCollection); @@ -1963,7 +1963,7 @@ private bool PublishBranch_PublishCultures(IContent content, HashSet cul // variant content type - publish specified cultures // invariant content type - publish only the invariant culture - var publishTime = DateTime.Now; + var publishTime = DateTime.UtcNow; if (content.ContentType.VariesByCulture()) { return culturesToPublish.All(culture => @@ -2378,7 +2378,7 @@ public void DeleteVersion(int id, int versionId, bool deletePriorVersions, int u if (deletePriorVersions) { IContent? content = GetVersion(versionId); - DeleteVersions(id, content?.UpdateDate ?? DateTime.Now, userId); + DeleteVersions(id, content?.UpdateDate ?? DateTime.UtcNow, userId); } scope.WriteLock(Constants.Locks.ContentTree); @@ -3162,7 +3162,7 @@ private PublishResult StrategyCanPublish( .ToArray(); // publish the culture(s) - var publishTime = DateTime.Now; + var publishTime = DateTime.UtcNow; if (!impactsToPublish.All(impact => content.PublishCulture(impact, publishTime, _propertyEditorCollection))) { return new PublishResult(PublishResultType.FailedPublishContentInvalid, evtMsgs, content); @@ -3430,7 +3430,7 @@ private PublishResult StrategyUnpublish(IContent content, EventMessages evtMsgs) // otherwise it would remain released == published ContentScheduleCollection contentSchedule = _documentRepository.GetContentSchedule(content.Id); IReadOnlyList pastReleases = - contentSchedule.GetPending(ContentScheduleAction.Expire, DateTime.Now); + contentSchedule.GetPending(ContentScheduleAction.Expire, DateTime.UtcNow); foreach (ContentSchedule p in pastReleases) { contentSchedule.Remove(p); @@ -3705,7 +3705,7 @@ public IContent CreateBlueprintFromContent( scope.Complete(); } - DateTime now = DateTime.Now; + DateTime now = DateTime.UtcNow; foreach (var culture in cultures) { foreach (IProperty property in blueprint.Properties) diff --git a/src/Umbraco.Core/Services/KeyValueService.cs b/src/Umbraco.Core/Services/KeyValueService.cs index e2c318fd0b93..3f81fa82a1d6 100644 --- a/src/Umbraco.Core/Services/KeyValueService.cs +++ b/src/Umbraco.Core/Services/KeyValueService.cs @@ -43,12 +43,12 @@ public void SetValue(string key, string value) IKeyValue? keyValue = _repository.Get(key); if (keyValue == null) { - keyValue = new KeyValue { Identifier = key, Value = value, UpdateDate = DateTime.Now }; + keyValue = new KeyValue { Identifier = key, Value = value, UpdateDate = DateTime.UtcNow }; } else { keyValue.Value = value; - keyValue.UpdateDate = DateTime.Now; + keyValue.UpdateDate = DateTime.UtcNow; } _repository.Save(keyValue); @@ -80,7 +80,7 @@ public bool TrySetValue(string key, string originalValue, string newValue) } keyValue.Value = newValue; - keyValue.UpdateDate = DateTime.Now; + keyValue.UpdateDate = DateTime.UtcNow; _repository.Save(keyValue); scope.Complete(); diff --git a/src/Umbraco.Core/Services/LogViewerService.cs b/src/Umbraco.Core/Services/LogViewerService.cs index 0780838416a9..30f3fd4b36bf 100644 --- a/src/Umbraco.Core/Services/LogViewerService.cs +++ b/src/Umbraco.Core/Services/LogViewerService.cs @@ -187,7 +187,7 @@ private LogTimePeriod GetTimePeriod(DateTimeOffset? startDate, DateTimeOffset? e { if (startDate is null || endDate is null) { - DateTime now = DateTime.Now; + DateTime now = DateTime.UtcNow; if (startDate is null) { startDate = now.AddDays(-1); diff --git a/src/Umbraco.Core/Services/ServerRegistrationService.cs b/src/Umbraco.Core/Services/ServerRegistrationService.cs index 070e9e8e1f52..569b1e43e6a0 100644 --- a/src/Umbraco.Core/Services/ServerRegistrationService.cs +++ b/src/Umbraco.Core/Services/ServerRegistrationService.cs @@ -55,12 +55,12 @@ public void TouchServer(string serverAddress, TimeSpan staleTimeout) if (server == null) { - server = new ServerRegistration(serverAddress, serverIdentity, DateTime.Now); + server = new ServerRegistration(serverAddress, serverIdentity, DateTime.UtcNow); } else { server.ServerAddress = serverAddress; // should not really change but it might! - server.UpdateDate = DateTime.Now; + server.UpdateDate = DateTime.UtcNow; } server.IsActive = true; diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index 718ef1eb6918..d7bb4034446e 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -787,7 +787,7 @@ public async Task> InviteAsyn throw new PanicException("Was unable to get user after creating it"); } - invitedUser.InvitedDate = DateTime.Now; + invitedUser.InvitedDate = DateTime.UtcNow; invitedUser.ClearGroups(); foreach(IUserGroup userGroup in userGroups) { @@ -827,7 +827,7 @@ public async Task> ResendInvi } // re-inviting so update invite date - invitedUser.InvitedDate = DateTime.Now; + invitedUser.InvitedDate = DateTime.UtcNow; await userStore.SaveAsync(invitedUser); Attempt invitationAttempt = await SendInvitationAsync(performingUser, serviceScope, invitedUser, model.Message); diff --git a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ContentVersionCleanupJob.cs b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ContentVersionCleanupJob.cs index cb89d600aa1d..b5d826bbe886 100644 --- a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ContentVersionCleanupJob.cs +++ b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/ContentVersionCleanupJob.cs @@ -50,7 +50,7 @@ public Task RunJobAsync() } - var count = _service.PerformContentVersionCleanup(DateTime.Now).Count; + var count = _service.PerformContentVersionCleanup(DateTime.UtcNow).Count; if (count > 0) { diff --git a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/WebhookLoggingCleanup.cs b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/WebhookLoggingCleanup.cs index 2e0bdc5edd10..8a76898923d6 100644 --- a/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/WebhookLoggingCleanup.cs +++ b/src/Umbraco.Infrastructure/BackgroundJobs/Jobs/WebhookLoggingCleanup.cs @@ -53,7 +53,7 @@ public async Task RunJobAsync() using (ICoreScope scope = _coreScopeProvider.CreateCoreScope()) { scope.ReadLock(Constants.Locks.WebhookLogs); - webhookLogs = await _webhookLogRepository.GetOlderThanDate(DateTime.Now - TimeSpan.FromDays(_webhookSettings.KeepLogsForDays)); + webhookLogs = await _webhookLogRepository.GetOlderThanDate(DateTime.UtcNow - TimeSpan.FromDays(_webhookSettings.KeepLogsForDays)); scope.Complete(); } diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseDataCreator.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseDataCreator.cs index e99ce4658731..ffb61e72202a 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseDataCreator.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseDataCreator.cs @@ -253,7 +253,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = new Guid(uniqueId), Text = text, NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }; ConditionalInsert( @@ -277,7 +277,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = new Guid("916724a5-173d-4619-b97e-b9de133dd6f5"), Text = "SYSTEM DATA: umbraco master root", NodeObjectType = Constants.ObjectTypes.SystemRoot, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }); _database.Insert(Constants.DatabaseSchema.Tables.Node, "id", false, new NodeDto @@ -292,7 +292,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.System.RecycleBinContentKey, Text = "Recycle Bin", NodeObjectType = Constants.ObjectTypes.ContentRecycleBin, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }); _database.Insert(Constants.DatabaseSchema.Tables.Node, "id", false, new NodeDto @@ -307,7 +307,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.System.RecycleBinMediaKey, Text = "Recycle Bin", NodeObjectType = Constants.ObjectTypes.MediaRecycleBin, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }); InsertDataTypeNodeDto(Constants.DataTypes.LabelString, 35, Constants.DataTypes.Guids.LabelString, @@ -336,7 +336,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.UploadGuid, Text = "Upload File", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -355,7 +355,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.UploadVideoGuid, Text = "Upload Video", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -374,7 +374,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.UploadAudioGuid, Text = "Upload Audio", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -393,7 +393,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.UploadArticleGuid, Text = "Upload Article", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -412,7 +412,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.UploadVectorGraphicsGuid, Text = "Upload Vector Graphics", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -431,7 +431,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.TextareaGuid, Text = "Textarea", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -450,7 +450,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.TextstringGuid, Text = "Textstring", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -469,7 +469,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.RichtextEditorGuid, Text = "Richtext editor", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -488,7 +488,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.NumericGuid, Text = "Numeric", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -507,7 +507,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.CheckboxGuid, Text = "True/false", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -526,7 +526,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.CheckboxListGuid, Text = "Checkbox list", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -545,7 +545,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.DropdownGuid, Text = "Dropdown", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -564,7 +564,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.DatePickerGuid, Text = "Date Picker", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -583,7 +583,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.RadioboxGuid, Text = "Radiobox", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -602,7 +602,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.DropdownMultipleGuid, Text = "Dropdown multiple", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -621,7 +621,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.ApprovedColorGuid, Text = "Approved Color", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -640,7 +640,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.DatePickerWithTimeGuid, Text = "Date Picker with time", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -659,7 +659,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.ListViewContentGuid, Text = Constants.Conventions.DataTypes.ListViewPrefix + "Content", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -678,7 +678,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.ListViewMediaGuid, Text = Constants.Conventions.DataTypes.ListViewPrefix + "Media", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -697,7 +697,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.TagsGuid, Text = "Tags", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -716,7 +716,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.ImageCropperGuid, Text = "Image Cropper", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -737,7 +737,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.ContentPickerGuid, Text = "Content Picker", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -756,7 +756,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.MemberPickerGuid, Text = "Member Picker", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -776,7 +776,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.RelatedLinksGuid, Text = "Multi URL Picker", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -796,7 +796,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.MediaPicker3Guid, Text = "Media Picker", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -815,7 +815,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.MediaPicker3MultipleGuid, Text = "Multiple Media Picker", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -834,7 +834,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.MediaPicker3SingleImageGuid, Text = "Image Media Picker", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -853,7 +853,7 @@ void InsertDataTypeNodeDto(int id, int sortOrder, string uniqueId, string text) UniqueId = Constants.DataTypes.Guids.MediaPicker3MultipleImagesGuid, Text = "Multiple Image Media Picker", NodeObjectType = Constants.ObjectTypes.DataType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -877,7 +877,7 @@ private void CreateNodeDataForMediaTypes() UniqueId = folderUniqueId, Text = Constants.Conventions.MediaTypes.Folder, NodeObjectType = Constants.ObjectTypes.MediaType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -898,7 +898,7 @@ private void CreateNodeDataForMediaTypes() UniqueId = imageUniqueId, Text = Constants.Conventions.MediaTypes.Image, NodeObjectType = Constants.ObjectTypes.MediaType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -919,7 +919,7 @@ private void CreateNodeDataForMediaTypes() UniqueId = fileUniqueId, Text = Constants.Conventions.MediaTypes.File, NodeObjectType = Constants.ObjectTypes.MediaType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -940,7 +940,7 @@ private void CreateNodeDataForMediaTypes() UniqueId = videoUniqueId, Text = Constants.Conventions.MediaTypes.Video, NodeObjectType = Constants.ObjectTypes.MediaType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -961,7 +961,7 @@ private void CreateNodeDataForMediaTypes() UniqueId = audioUniqueId, Text = Constants.Conventions.MediaTypes.Audio, NodeObjectType = Constants.ObjectTypes.MediaType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -982,7 +982,7 @@ private void CreateNodeDataForMediaTypes() UniqueId = articleUniqueId, Text = Constants.Conventions.MediaTypes.Article, NodeObjectType = Constants.ObjectTypes.MediaType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -1003,7 +1003,7 @@ private void CreateNodeDataForMediaTypes() UniqueId = svgUniqueId, Text = "Vector Graphics (SVG)", NodeObjectType = Constants.ObjectTypes.MediaType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -1027,7 +1027,7 @@ private void CreateNodeDataForMemberTypes() UniqueId = memberUniqueId, Text = Constants.Conventions.MemberTypes.DefaultAlias, NodeObjectType = Constants.ObjectTypes.MemberType, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }, Constants.DatabaseSchema.Tables.Node, "id"); @@ -1194,8 +1194,8 @@ private void CreateUserData() => _database.Insert(Constants.DatabaseSchema.Table Password = "default", Email = string.Empty, UserLanguage = "en-US", - CreateDate = DateTime.Now, - UpdateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, + UpdateDate = DateTime.UtcNow, }); private void CreateUserGroupData() @@ -1212,8 +1212,8 @@ private void CreateUserGroupData() StartContentId = -1, Alias = Constants.Security.AdminGroupAlias, Name = "Administrators", - CreateDate = DateTime.Now, - UpdateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, + UpdateDate = DateTime.UtcNow, Icon = "icon-medal", HasAccessToAllLanguages = true, }); @@ -1229,8 +1229,8 @@ private void CreateUserGroupData() StartContentId = -1, Alias = WriterGroupAlias, Name = "Writers", - CreateDate = DateTime.Now, - UpdateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, + UpdateDate = DateTime.UtcNow, Icon = "icon-edit", HasAccessToAllLanguages = true, }); @@ -1246,8 +1246,8 @@ private void CreateUserGroupData() StartContentId = -1, Alias = EditorGroupAlias, Name = "Editors", - CreateDate = DateTime.Now, - UpdateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, + UpdateDate = DateTime.UtcNow, Icon = "icon-tools", HasAccessToAllLanguages = true, }); @@ -1263,8 +1263,8 @@ private void CreateUserGroupData() StartContentId = -1, Alias = TranslatorGroupAlias, Name = "Translators", - CreateDate = DateTime.Now, - UpdateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, + UpdateDate = DateTime.UtcNow, Icon = "icon-globe", HasAccessToAllLanguages = true, }); @@ -1278,8 +1278,8 @@ private void CreateUserGroupData() Key = Constants.Security.SensitiveDataGroupKey, Alias = SensitiveDataGroupAlias, Name = "Sensitive data", - CreateDate = DateTime.Now, - UpdateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, + UpdateDate = DateTime.UtcNow, Icon = "icon-lock", HasAccessToAllLanguages = false, }); @@ -2340,7 +2340,7 @@ private void CreateKeyValueData() var finalState = upgrader.Plan.FinalState; _database.Insert(Constants.DatabaseSchema.Tables.KeyValue, "key", false, - new KeyValueDto { Key = stateValueKey, Value = finalState, UpdateDate = DateTime.Now }); + new KeyValueDto { Key = stateValueKey, Value = finalState, UpdateDate = DateTime.UtcNow }); upgrader = new Upgrader(new UmbracoPremigrationPlan()); @@ -2348,7 +2348,7 @@ private void CreateKeyValueData() finalState = upgrader.Plan.FinalState; _database.Insert(Constants.DatabaseSchema.Tables.KeyValue, "key", false, - new KeyValueDto { Key = stateValueKey, Value = finalState, UpdateDate = DateTime.Now }); + new KeyValueDto { Key = stateValueKey, Value = finalState, UpdateDate = DateTime.UtcNow }); } private void CreateLogViewerQueryData() diff --git a/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs b/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs index b02c56fea699..4089b080a94e 100644 --- a/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs +++ b/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs @@ -126,5 +126,7 @@ protected virtual void DefinePlan() // To 17.0.0 To("{17D5F6CA-CEB8-462A-AF86-4B9C3BF91CF1}"); + To("{1847C7FF-B021-44EB-BEB0-A77A4376A6F2}"); + To("{7208B20D-6BFC-472E-9374-85EEA817B27D}"); } } diff --git a/src/Umbraco.Infrastructure/Migrations/Upgrade/V_17_0_0/MigrateSystemDatesToUtc.cs b/src/Umbraco.Infrastructure/Migrations/Upgrade/V_17_0_0/MigrateSystemDatesToUtc.cs new file mode 100644 index 000000000000..25959f3ffdd8 --- /dev/null +++ b/src/Umbraco.Infrastructure/Migrations/Upgrade/V_17_0_0/MigrateSystemDatesToUtc.cs @@ -0,0 +1,144 @@ +using NPoco; +using Umbraco.Cms.Infrastructure.Scoping; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Umbraco.Cms.Core.Configuration.Models; + +namespace Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_17_0_0; + +/// +/// Adds a migration to transform all system dates stored in the database from the local server timezone to UTC. +/// +public class MigrateSystemDatesToUtc : UnscopedMigrationBase +{ + private readonly IScopeProvider _scopeProvider; + private readonly TimeProvider _timeProvider; + private readonly IOptions _migrationSettings; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + /// + public MigrateSystemDatesToUtc( + IMigrationContext context, + IScopeProvider scopeProvider, + TimeProvider timeProvider, + IOptions migrationSettings, + ILogger logger) + : base(context) + { + _scopeProvider = scopeProvider; + _timeProvider = timeProvider; + _migrationSettings = migrationSettings; + _logger = logger; + } + + /// + protected override void Migrate() + { + if (_migrationSettings.Value.Enabled is false) + { + // If the migration is disabled, we do nothing. + _logger.LogInformation("Skipping migration {MigrationName} as it is disabled in the configuration.", nameof(MigrateSystemDatesToUtc)); + Context.Complete(); + return; + } + + // If the local server timezone is not set, we detect it. + var timeZoneName = _migrationSettings.Value.LocalServerTimeZone; + if (string.IsNullOrWhiteSpace(timeZoneName)) + { + timeZoneName = _timeProvider.LocalTimeZone.StandardName; + _logger.LogInformation("Migrating system dates to UTC using the detected local server timezone: {TimeZoneName}.", timeZoneName); + } + else + { + _logger.LogInformation("Migrating system dates to UTC using the configured local server timezone: {TimeZoneName}.", timeZoneName); + } + + // If the local server timezone is UTC, skip the migration. + if (string.Equals(timeZoneName, "Coordinated Universal Time", StringComparison.OrdinalIgnoreCase)) + { + _logger.LogInformation("Skipping migration {MigrationName} as the local server timezone is UTC.", nameof(MigrateSystemDatesToUtc)); + Context.Complete(); + return; + } + + TimeSpan timeZoneOffset = GetTimezoneOffset(timeZoneName); + + using IScope scope = _scopeProvider.CreateScope(); + using IDisposable notificationSuppression = scope.Notifications.Suppress(); + + MigrateDateColumn(scope, "cmsMember", "emailConfirmedDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "cmsMember", "lastLoginDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "cmsMember", "lastLockoutDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "cmsMember", "lastPasswordChangeDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoAccess", "createDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoAccess", "updateDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoAccessRule", "createDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoAccessRule", "updateDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoCreatedPackageSchema", "updateDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoContentVersion", "versionDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoContentVersionCleanupPolicy", "updated", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoContentVersionCultureVariation", "date", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoExternalLogin", "createDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoExternalLoginToken", "createDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoKeyValue", "updated", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoLog", "Datestamp", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoNode", "createDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoRelation", "datetime", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoServer", "registeredDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoServer", "lastNotifiedDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoUser", "createDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoUser", "updateDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoUser", "emailConfirmedDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoUser", "lastLockoutDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoUser", "lastPasswordChangeDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoUser", "lastLoginDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoUser", "invitedDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoUserGroup", "createDate", timeZoneName, timeZoneOffset); + MigrateDateColumn(scope, "umbracoUserGroup", "updateDate", timeZoneName, timeZoneOffset); + + scope.Complete(); + Context.Complete(); + } + + private static TimeSpan GetTimezoneOffset(string timeZoneName) + + // We know the provided timezone name exists, as it's either detected or configured (and configuration has been validated). + => TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).BaseUtcOffset; + + private void MigrateDateColumn(IScope scope, string tableName, string columName, string timezoneName, TimeSpan timeZoneOffset) + { + var offsetInMinutes = -timeZoneOffset.TotalMinutes; + var offSetInMinutesString = offsetInMinutes > 0 + ? $"+{offsetInMinutes}" + : $"{offsetInMinutes}"; + + Sql sql; + if (DatabaseType == DatabaseType.SQLite) + { + // SQLite does not support AT TIME ZONE, but we can use the offset to update the dates. It won't take account of daylight saving time, but + // given these are historical dates in expected non-production environments, that are unlikely to be necessary to be 100% accurate, this is acceptable. + sql = Sql($"UPDATE {tableName} SET {columName} = DATETIME({columName}, '{offSetInMinutesString} minutes')"); + } + else + { + sql = Sql($"UPDATE {tableName} SET {columName} = {columName} AT TIME ZONE '{timezoneName}' AT TIME ZONE 'UTC'"); + } + + scope.Database.Execute(sql); + + _logger.LogInformation( + "Migrated {TableName}.{ColumnName} from local server timezone of {TimeZoneName} ({OffSetInMinutes} minutes) to UTC.", + tableName, + columName, + timezoneName, + offSetInMinutesString); + } +} diff --git a/src/Umbraco.Infrastructure/Migrations/Upgrade/V_17_0_0/SetDateDefaultsToUtcNow.cs b/src/Umbraco.Infrastructure/Migrations/Upgrade/V_17_0_0/SetDateDefaultsToUtcNow.cs new file mode 100644 index 000000000000..5c329dfffbb6 --- /dev/null +++ b/src/Umbraco.Infrastructure/Migrations/Upgrade/V_17_0_0/SetDateDefaultsToUtcNow.cs @@ -0,0 +1,81 @@ +using NPoco; +using Umbraco.Cms.Infrastructure.Scoping; + +namespace Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_17_0_0; + +/// +/// Defines a migration to convert database date default constraints from local time to UTC. +/// +public class SetDateDefaultsToUtcNow : UnscopedMigrationBase +{ + private readonly IScopeProvider _scopeProvider; + + /// + /// Initializes a new instance of the class. + /// + /// + /// + public SetDateDefaultsToUtcNow(IMigrationContext context, IScopeProvider scopeProvider) + : base(context) => _scopeProvider = scopeProvider; + + protected override void Migrate() + { + if (DatabaseType == DatabaseType.SQLite) + { + MigrateSqlite(); + } + else + { + MigrateSqlServer(); + } + + Context.Complete(); + } + + private void MigrateSqlite() + { + // SQLite doesn't fully support ALTER TABLE so to migrate we would need to create a new table and copy in the data. + // However the previous defaults have been set to "DATE()", which isn't a sensible choice anyway as it has no time component. + // Given that, it seems very unlikely we are using these database defaults in any meaningful way, and are instead providing + // values for all date fields when saving. + // As such we don't need to migrate these. + } + + private void MigrateSqlServer() + { + using IScope scope = _scopeProvider.CreateScope(); + using IDisposable notificationSuppression = scope.Notifications.Suppress(); + ScopeDatabase(scope); + + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.Access, "createDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.Access, "updateDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.AccessRule, "createDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.AccessRule, "updateDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.AuditEntry, "eventDateUtc"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.Consent, "createDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.ContentVersion, "versionDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.CreatedPackageSchema, "updateDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.ExternalLogin, "createDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.ExternalLoginToken, "createDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.KeyValue, "updated"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.Log, "Datestamp"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.Node, "createDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.Relation, "datetime"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.Server, "registeredDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.User, "createDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.User, "updateDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.UserGroup, "createDate"); + ModifySqlServerDefaultDateConstraint(scope, Core.Constants.DatabaseSchema.Tables.UserGroup, "updateDate"); + + Context.Complete(); + + scope.Complete(); + } + + private static void ModifySqlServerDefaultDateConstraint(IScope scope, string tableName, string columnName) + { + var constraintName = $"DF_{tableName}_{columnName}"; + scope.Database.Execute($"ALTER TABLE {tableName} DROP CONSTRAINT {constraintName}"); + scope.Database.Execute($"ALTER TABLE {tableName} ADD CONSTRAINT {constraintName} DEFAULT GETUTCDATE() FOR {columnName}"); + } +} diff --git a/src/Umbraco.Infrastructure/Persistence/DatabaseModelDefinitions/SystemMethods.cs b/src/Umbraco.Infrastructure/Persistence/DatabaseModelDefinitions/SystemMethods.cs index 6836b965827e..375c442864dc 100644 --- a/src/Umbraco.Infrastructure/Persistence/DatabaseModelDefinitions/SystemMethods.cs +++ b/src/Umbraco.Infrastructure/Persistence/DatabaseModelDefinitions/SystemMethods.cs @@ -1,11 +1,22 @@ namespace Umbraco.Cms.Infrastructure.Persistence.DatabaseModelDefinitions; +/// +/// Defines options available for default values derived from database system methods. +/// public enum SystemMethods { + /// + /// Represents a default value that is a generated GUID. + /// NewGuid, + /// + /// Represents a default value that is the current date time. + /// CurrentDateTime, - // NewSequentialId, - // CurrentUTCDateTime + /// + /// Represents a default value that is the current UTC date time. + /// + CurrentUTCDateTime, } diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/AccessDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/AccessDto.cs index dcd62d54d3b6..cfde523e286e 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/AccessDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/AccessDto.cs @@ -27,12 +27,12 @@ internal sealed class AccessDto [ForeignKey(typeof(NodeDto), Name = "FK_umbracoAccess_umbracoNode_id2")] public int NoAccessNodeId { get; set; } - [Column("createDate", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("createDate")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime CreateDate { get; set; } - [Column("updateDate", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("updateDate")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime UpdateDate { get; set; } [ResultColumn] diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/AccessRuleDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/AccessRuleDto.cs index bc8c92addffa..ae0e654bd222 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/AccessRuleDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/AccessRuleDto.cs @@ -25,11 +25,11 @@ internal sealed class AccessRuleDto [Column("ruleType")] public string? RuleType { get; set; } - [Column("createDate", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("createDate")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime CreateDate { get; set; } - [Column("updateDate", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("updateDate")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime UpdateDate { get; set; } } diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/AuditEntryDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/AuditEntryDto.cs index ccdafbb0f095..e8d8a2052ccf 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/AuditEntryDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/AuditEntryDto.cs @@ -34,9 +34,9 @@ internal sealed class AuditEntryDto [Length(Constants.Audit.IpLength)] public string? PerformingIp { get; set; } - [Column("eventDateUtc", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] - public DateTime EventDateUtc { get; set; } + [Column("eventDateUtc")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] + public DateTime EventDate { get; set; } [Column("affectedUserId")] public int AffectedUserId { get; set; } diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/ConsentDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/ConsentDto.cs index 67db05a3cf00..e205869c56eb 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/ConsentDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/ConsentDto.cs @@ -29,8 +29,8 @@ public class ConsentDto [Length(512)] public string? Action { get; set; } - [Column("createDate", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("createDate")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime CreateDate { get; set; } [Column("state")] diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionCleanupPolicyDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionCleanupPolicyDto.cs index 2e024541a74f..9a808bf6f101 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionCleanupPolicyDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionCleanupPolicyDto.cs @@ -27,6 +27,6 @@ internal sealed class ContentVersionCleanupPolicyDto [NullSetting(NullSetting = NullSettings.Null)] public int? KeepLatestVersionPerDayForDays { get; set; } - [Column("updated", ForceToUtc = false)] + [Column("updated")] public DateTime Updated { get; set; } } diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionCultureVariationDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionCultureVariationDto.cs index c868ba4afbe5..faa3ad4f1f8e 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionCultureVariationDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionCultureVariationDto.cs @@ -33,7 +33,7 @@ internal sealed class ContentVersionCultureVariationDto [Column("name")] public string? Name { get; set; } - [Column("date", ForceToUtc = false)] // TODO: db rename to 'updateDate' + [Column("date")] // TODO: db rename to 'updateDate' public DateTime UpdateDate { get; set; } [Column("availableUserId")] // TODO: db rename to 'updateDate' diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionDto.cs index e05bcf0d0524..a3302be04673 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/ContentVersionDto.cs @@ -22,8 +22,8 @@ public class ContentVersionDto [Index(IndexTypes.NonClustered, Name = "IX_" + TableName + "_NodeId", ForColumns = "nodeId,current", IncludeColumns = "id,versionDate,text,userId,preventCleanup")] public int NodeId { get; set; } - [Column("versionDate", ForceToUtc = false)] // TODO: db rename to 'updateDate' - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("versionDate")] // TODO: db rename to 'updateDate' + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime VersionDate { get; set; } [Column("userId")] // TODO: db rename to 'updateUserId' diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/CreatedPackageSchemaDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/CreatedPackageSchemaDto.cs index 07ac53d552c8..52eb4bb7e3d3 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/CreatedPackageSchemaDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/CreatedPackageSchemaDto.cs @@ -27,8 +27,8 @@ public class CreatedPackageSchemaDto [NullSetting(NullSetting = NullSettings.NotNull)] public string Value { get; set; } = null!; - [Column("updateDate", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("updateDate")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime UpdateDate { get; set; } [Column("packageId")] diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/DocumentPublishedReadOnlyDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/DocumentPublishedReadOnlyDto.cs deleted file mode 100644 index 04fb1017e80b..000000000000 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/DocumentPublishedReadOnlyDto.cs +++ /dev/null @@ -1,25 +0,0 @@ -using NPoco; -using Umbraco.Cms.Core; - -namespace Umbraco.Cms.Infrastructure.Persistence.Dtos; - -[TableName(Constants.DatabaseSchema.Tables.Document)] -[PrimaryKey("versionId", AutoIncrement = false)] -[ExplicitColumns] -internal sealed class DocumentPublishedReadOnlyDto -{ - [Column("nodeId")] - public int NodeId { get; set; } - - [Column("published")] - public bool Published { get; set; } - - [Column("versionId")] - public Guid VersionId { get; set; } - - [Column("newest")] - public bool Newest { get; set; } - - [Column("updateDate", ForceToUtc = false)] - public DateTime VersionDate { get; set; } -} diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/ExternalLoginDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/ExternalLoginDto.cs index 3d84dbafe6f1..8720542ee6e0 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/ExternalLoginDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/ExternalLoginDto.cs @@ -42,8 +42,8 @@ internal sealed class ExternalLoginDto [Index(IndexTypes.NonClustered, ForColumns = "loginProvider,providerKey", Name = "IX_" + TableName + "_ProviderKey")] public string ProviderKey { get; set; } = null!; - [Column("createDate", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("createDate")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime CreateDate { get; set; } /// diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/ExternalLoginTokenDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/ExternalLoginTokenDto.cs index 7ff2622960f1..9e937f8d79a3 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/ExternalLoginTokenDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/ExternalLoginTokenDto.cs @@ -31,8 +31,8 @@ internal sealed class ExternalLoginTokenDto [NullSetting(NullSetting = NullSettings.NotNull)] public string Value { get; set; } = null!; - [Column("createDate", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("createDate")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime CreateDate { get; set; } [ResultColumn] diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/KeyValueDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/KeyValueDto.cs index 51d2a7412152..028eb0f52a14 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/KeyValueDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/KeyValueDto.cs @@ -23,8 +23,8 @@ internal sealed class KeyValueDto [NullSetting(NullSetting = NullSettings.Null)] public string? Value { get; set; } - [Column("updated", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("updated")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime UpdateDate { get; set; } //NOTE that changes to this file needs to be backward compatible. Otherwise our upgrader cannot work, as it uses this to read from the db diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/LogDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/LogDto.cs index 20c2733bfefb..3abc067dad26 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/LogDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/LogDto.cs @@ -35,8 +35,8 @@ internal sealed class LogDto [NullSetting(NullSetting = NullSettings.Null)] public string? EntityType { get; set; } - [Column("Datestamp", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("Datestamp")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] [Index(IndexTypes.NonClustered, Name = "IX_" + TableName + "_datestamp", ForColumns = "Datestamp,userId,NodeId")] public DateTime Datestamp { get; set; } diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/MemberDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/MemberDto.cs index 99d07e2276e8..98435f8ce082 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/MemberDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/MemberDto.cs @@ -45,7 +45,7 @@ internal sealed class MemberDto [Length(255)] public string? SecurityStampToken { get; set; } - [Column("emailConfirmedDate", ForceToUtc = false)] + [Column("emailConfirmedDate")] [NullSetting(NullSetting = NullSettings.Null)] public DateTime? EmailConfirmedDate { get; set; } @@ -62,15 +62,15 @@ internal sealed class MemberDto [Constraint(Default = 1)] public bool IsApproved { get; set; } - [Column("lastLoginDate", ForceToUtc = false)] + [Column("lastLoginDate")] [NullSetting(NullSetting = NullSettings.Null)] public DateTime? LastLoginDate { get; set; } - [Column("lastLockoutDate", ForceToUtc = false)] + [Column("lastLockoutDate")] [NullSetting(NullSetting = NullSettings.Null)] public DateTime? LastLockoutDate { get; set; } - [Column("lastPasswordChangeDate", ForceToUtc = false)] + [Column("lastPasswordChangeDate")] [NullSetting(NullSetting = NullSettings.Null)] public DateTime? LastPasswordChangeDate { get; set; } diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/NodeDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/NodeDto.cs index e140b3ec5d1d..f90824c51ecc 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/NodeDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/NodeDto.cs @@ -70,7 +70,7 @@ public class NodeDto [Index(IndexTypes.NonClustered, Name = "IX_" + TableName + "_ObjectType", ForColumns = "nodeObjectType,trashed", IncludeColumns = "uniqueId,parentId,level,path,sortOrder,nodeUser,text,createDate")] public Guid? NodeObjectType { get; set; } - [Column("createDate", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("createDate")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime CreateDate { get; set; } } diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/RelationDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/RelationDto.cs index a05fc94cd64f..72c0877c6aed 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/RelationDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/RelationDto.cs @@ -27,8 +27,8 @@ internal sealed class RelationDto [ForeignKey(typeof(RelationTypeDto))] public int RelationType { get; set; } - [Column("datetime", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("datetime")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime Datetime { get; set; } [Column("comment")] diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/ServerRegistrationDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/ServerRegistrationDto.cs index bc08d9a4a132..28a6fbe6cefd 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/ServerRegistrationDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/ServerRegistrationDto.cs @@ -23,11 +23,11 @@ internal sealed class ServerRegistrationDto [Index(IndexTypes.UniqueNonClustered, Name = "IX_computerName")] // server identity is unique public string? ServerIdentity { get; set; } - [Column("registeredDate", ForceToUtc = false)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Column("registeredDate")] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime DateRegistered { get; set; } - [Column("lastNotifiedDate", ForceToUtc = false)] + [Column("lastNotifiedDate")] public DateTime DateAccessed { get; set; } [Column("isActive")] diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/UserDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/UserDto.cs index 497233256637..abc655c3db64 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/UserDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/UserDto.cs @@ -73,35 +73,35 @@ public UserDto() [NullSetting(NullSetting = NullSettings.Null)] public int? FailedLoginAttempts { get; set; } - [Column("lastLockoutDate", ForceToUtc = false)] + [Column("lastLockoutDate")] [NullSetting(NullSetting = NullSettings.Null)] public DateTime? LastLockoutDate { get; set; } - [Column("lastPasswordChangeDate", ForceToUtc = false)] + [Column("lastPasswordChangeDate")] [NullSetting(NullSetting = NullSettings.Null)] public DateTime? LastPasswordChangeDate { get; set; } - [Column("lastLoginDate", ForceToUtc = false)] + [Column("lastLoginDate")] [NullSetting(NullSetting = NullSettings.Null)] public DateTime? LastLoginDate { get; set; } - [Column("emailConfirmedDate", ForceToUtc = false)] + [Column("emailConfirmedDate")] [NullSetting(NullSetting = NullSettings.Null)] public DateTime? EmailConfirmedDate { get; set; } - [Column("invitedDate", ForceToUtc = false)] + [Column("invitedDate")] [NullSetting(NullSetting = NullSettings.Null)] public DateTime? InvitedDate { get; set; } - [Column("createDate", ForceToUtc = false)] + [Column("createDate")] [NullSetting(NullSetting = NullSettings.NotNull)] - [Constraint(Default = SystemMethods.CurrentDateTime)] - public DateTime CreateDate { get; set; } = DateTime.Now; + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] + public DateTime CreateDate { get; set; } = DateTime.UtcNow; - [Column("updateDate", ForceToUtc = false)] + [Column("updateDate")] [NullSetting(NullSetting = NullSettings.NotNull)] - [Constraint(Default = SystemMethods.CurrentDateTime)] - public DateTime UpdateDate { get; set; } = DateTime.Now; + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] + public DateTime UpdateDate { get; set; } = DateTime.UtcNow; [Column("kind")] [NullSetting(NullSetting = NullSettings.NotNull)] diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/UserGroupDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/UserGroupDto.cs index cf66725f3678..794eceeff5f1 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/UserGroupDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/UserGroupDto.cs @@ -44,14 +44,14 @@ public UserGroupDto() [Obsolete("Is not used anymore Use UserGroup2PermissionDtos instead. This will be removed in Umbraco 18.")] public string? DefaultPermissions { get; set; } - [Column("createDate", ForceToUtc = false)] + [Column("createDate")] [NullSetting(NullSetting = NullSettings.NotNull)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime CreateDate { get; set; } - [Column("updateDate", ForceToUtc = false)] + [Column("updateDate")] [NullSetting(NullSetting = NullSettings.NotNull)] - [Constraint(Default = SystemMethods.CurrentDateTime)] + [Constraint(Default = SystemMethods.CurrentUTCDateTime)] public DateTime UpdateDate { get; set; } [Column("icon")] diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/UserLoginDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/UserLoginDto.cs index 1c6d2d3464a0..6b7705e6b53b 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/UserLoginDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/UserLoginDto.cs @@ -24,7 +24,7 @@ internal sealed class UserLoginDto /// [Column("loggedInUtc")] [NullSetting(NullSetting = NullSettings.NotNull)] - public DateTime LoggedInUtc { get; set; } + public DateTime LoggedIn { get; set; } /// /// Updated every time a user's session is validated @@ -42,14 +42,14 @@ internal sealed class UserLoginDto [Column("lastValidatedUtc")] [NullSetting(NullSetting = NullSettings.NotNull)] [Index(IndexTypes.NonClustered, Name = "IX_umbracoUserLogin_lastValidatedUtc")] - public DateTime LastValidatedUtc { get; set; } + public DateTime LastValidated { get; set; } /// /// Tracks when the session is removed when the user's account is logged out /// [Column("loggedOutUtc")] [NullSetting(NullSetting = NullSettings.Null)] - public DateTime? LoggedOutUtc { get; set; } + public DateTime? LoggedOut { get; set; } /// /// Logs the IP address of the session if available diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/WebhookLogDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/WebhookLogDto.cs index fe02955e078a..c0f432a41707 100644 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/WebhookLogDto.cs +++ b/src/Umbraco.Infrastructure/Persistence/Dtos/WebhookLogDto.cs @@ -24,7 +24,7 @@ internal sealed class WebhookLogDto [NullSetting(NullSetting = NullSettings.NotNull)] public string StatusCode { get; set; } = string.Empty; - [Column(Name = "date", ForceToUtc = false)] + [Column(Name = "date")] [Index(IndexTypes.NonClustered, Name = "IX_" + Constants.DatabaseSchema.Tables.WebhookLog + "_date")] [NullSetting(NullSetting = NullSettings.NotNull)] public DateTime Date { get; set; } diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/AuditEntryFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/AuditEntryFactory.cs index 2d2d15211c5d..d5389d2b0352 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/AuditEntryFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/AuditEntryFactory.cs @@ -1,3 +1,4 @@ +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Infrastructure.Persistence.Dtos; @@ -17,7 +18,7 @@ public static IAuditEntry BuildEntity(AuditEntryDto dto) PerformingUserKey = dto.PerformingUserKey, PerformingDetails = dto.PerformingDetails, PerformingIp = dto.PerformingIp, - EventDateUtc = dto.EventDateUtc, + EventDate = dto.EventDate.EnsureUtc(), AffectedUserId = dto.AffectedUserId, AffectedUserKey = dto.AffectedUserKey, AffectedDetails = dto.AffectedDetails, @@ -39,7 +40,7 @@ public static AuditEntryDto BuildDto(IAuditEntry entity) => PerformingUserKey = entity.PerformingUserKey, PerformingDetails = entity.PerformingDetails, PerformingIp = entity.PerformingIp, - EventDateUtc = entity.EventDateUtc, + EventDate = entity.EventDate, AffectedUserId = entity.AffectedUserId, AffectedUserKey = entity.AffectedUserKey, AffectedDetails = entity.AffectedDetails, diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/AuditItemFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/AuditItemFactory.cs new file mode 100644 index 000000000000..f77ede99dc9e --- /dev/null +++ b/src/Umbraco.Infrastructure/Persistence/Factories/AuditItemFactory.cs @@ -0,0 +1,34 @@ +using Umbraco.Cms.Core; +using Umbraco.Cms.Core.Extensions; +using Umbraco.Cms.Core.Models; +using Umbraco.Cms.Infrastructure.Persistence.Dtos; + +namespace Umbraco.Cms.Infrastructure.Persistence.Factories; + +internal static class AuditItemFactory +{ + public static IEnumerable BuildEntities(IEnumerable dtos) => + dtos.Select(BuildEntity).ToList(); + + public static IAuditItem BuildEntity(LogDto dto) + => new AuditItem( + dto.NodeId, + Enum.ParseOrNull(dto.Header) ?? AuditType.Custom, + dto.UserId ?? Constants.Security.UnknownUserId, + dto.EntityType, + dto.Comment, + dto.Parameters, + dto.Datestamp.EnsureUtc()); + + public static LogDto BuildDto(IAuditItem entity) => + new LogDto + { + Comment = entity.Comment, + Datestamp = DateTime.UtcNow, + Header = entity.AuditType.ToString(), + NodeId = entity.Id, + UserId = entity.UserId, + EntityType = entity.EntityType, + Parameters = entity.Parameters, + }; +} diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/CacheInstructionFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/CacheInstructionFactory.cs index bc33b15fd5ce..220b81d86bd6 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/CacheInstructionFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/CacheInstructionFactory.cs @@ -1,3 +1,4 @@ +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Infrastructure.Persistence.Dtos; @@ -9,7 +10,7 @@ public static IEnumerable BuildEntities(IEnumerable - new(dto.Id, dto.UtcStamp, dto.Instructions, dto.OriginIdentity, dto.InstructionCount); + new(dto.Id, dto.UtcStamp.EnsureUtc(), dto.Instructions, dto.OriginIdentity, dto.InstructionCount); public static CacheInstructionDto BuildDto(CacheInstruction entity) => new() diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/ConsentFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/ConsentFactory.cs index 5e4035b0b8ac..bd28a3ad7b4f 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/ConsentFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/ConsentFactory.cs @@ -1,3 +1,4 @@ +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Infrastructure.Persistence.Dtos; @@ -18,7 +19,7 @@ public static IEnumerable BuildEntities(IEnumerable dtos) { Id = dto.Id, Current = dto.Current, - CreateDate = dto.CreateDate, + CreateDate = dto.CreateDate.EnsureUtc(), Source = dto.Source, Context = dto.Context, Action = dto.Action, diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/ContentBaseFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/ContentBaseFactory.cs index 01817252dc59..8d5cbdf0f1f4 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/ContentBaseFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/ContentBaseFactory.cs @@ -1,4 +1,5 @@ using Umbraco.Cms.Core; +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Persistence.Repositories; using Umbraco.Cms.Core.PropertyEditors; @@ -40,10 +41,8 @@ public static Content BuildEntity(DocumentDto dto, IContentType? contentType) content.CreatorId = nodeDto.UserId ?? Constants.Security.UnknownUserId; content.WriterId = contentVersionDto.UserId ?? Constants.Security.UnknownUserId; - // Dates stored in the database are local server time, but for SQL Server, will be considered - // as DateTime.Kind = Utc. Fix this so we are consistent when later mapping to DataTimeOffset. - content.CreateDate = DateTime.SpecifyKind(nodeDto.CreateDate, DateTimeKind.Local); - content.UpdateDate = DateTime.SpecifyKind(contentVersionDto.VersionDate, DateTimeKind.Local); + content.CreateDate = nodeDto.CreateDate.EnsureUtc(); + content.UpdateDate = contentVersionDto.VersionDate.EnsureUtc(); content.Published = dto.Published; content.Edited = dto.Edited; @@ -55,7 +54,7 @@ public static Content BuildEntity(DocumentDto dto, IContentType? contentType) content.PublishedVersionId = publishedVersionDto.Id; if (dto.Published) { - content.PublishDate = DateTime.SpecifyKind(publishedVersionDto.ContentVersionDto.VersionDate, DateTimeKind.Local); + content.PublishDate = publishedVersionDto.ContentVersionDto.VersionDate.EnsureUtc(); content.PublishName = publishedVersionDto.ContentVersionDto.Text; content.PublisherId = publishedVersionDto.ContentVersionDto.UserId; } @@ -100,8 +99,8 @@ public static Core.Models.Media BuildEntity(ContentDto dto, IMediaType? contentT content.CreatorId = nodeDto.UserId ?? Constants.Security.UnknownUserId; content.WriterId = contentVersionDto.UserId ?? Constants.Security.UnknownUserId; - content.CreateDate = DateTime.SpecifyKind(nodeDto.CreateDate, DateTimeKind.Local); - content.UpdateDate = DateTime.SpecifyKind(contentVersionDto.VersionDate, DateTimeKind.Local); + content.CreateDate = nodeDto.CreateDate.EnsureUtc(); + content.UpdateDate = contentVersionDto.VersionDate.EnsureUtc(); // reset dirty initial properties (U4-1946) content.ResetDirtyProperties(false); @@ -130,7 +129,7 @@ public static Member BuildEntity(MemberDto dto, IMemberType? contentType) content.Id = dto.NodeId; content.SecurityStamp = dto.SecurityStampToken; content.EmailConfirmedDate = dto.EmailConfirmedDate.HasValue - ? DateTime.SpecifyKind(dto.EmailConfirmedDate.Value, DateTimeKind.Local) + ? dto.EmailConfirmedDate.Value.EnsureUtc() : null; content.PasswordConfiguration = dto.PasswordConfig; content.Key = nodeDto.UniqueId; @@ -145,19 +144,19 @@ public static Member BuildEntity(MemberDto dto, IMemberType? contentType) content.CreatorId = nodeDto.UserId ?? Constants.Security.UnknownUserId; content.WriterId = contentVersionDto.UserId ?? Constants.Security.UnknownUserId; - content.CreateDate = DateTime.SpecifyKind(nodeDto.CreateDate, DateTimeKind.Local); - content.UpdateDate = DateTime.SpecifyKind(contentVersionDto.VersionDate, DateTimeKind.Local); + content.CreateDate = nodeDto.CreateDate.EnsureUtc(); + content.UpdateDate = contentVersionDto.VersionDate.EnsureUtc(); content.FailedPasswordAttempts = dto.FailedPasswordAttempts ?? default; content.IsLockedOut = dto.IsLockedOut; content.IsApproved = dto.IsApproved; content.LastLockoutDate = dto.LastLockoutDate.HasValue - ? DateTime.SpecifyKind(dto.LastLockoutDate.Value, DateTimeKind.Local) + ? dto.LastLockoutDate.Value.EnsureUtc() : null; content.LastLoginDate = dto.LastLoginDate.HasValue - ? DateTime.SpecifyKind(dto.LastLoginDate.Value, DateTimeKind.Local) + ? dto.LastLoginDate.Value.EnsureUtc() : null; content.LastPasswordChangeDate = dto.LastPasswordChangeDate.HasValue - ? DateTime.SpecifyKind(dto.LastPasswordChangeDate.Value, DateTimeKind.Local) + ? dto.LastPasswordChangeDate.Value.EnsureUtc() : null; // reset dirty initial properties (U4-1946) @@ -197,7 +196,7 @@ public static DocumentDto BuildDto(IContent entity, Guid objectType) new ContentScheduleDto { Action = x.Action.ToString(), - Date = DateTime.SpecifyKind(x.Date, DateTimeKind.Local), + Date = x.Date, NodeId = entity.Id, LanguageId = languageRepository.GetIdByIsoCode(x.Culture, false), Id = x.Id, @@ -272,7 +271,7 @@ private static NodeDto BuildNodeDto(IContentBase entity, Guid objectType) UserId = entity.CreatorId, Text = entity.Name, NodeObjectType = objectType, - CreateDate = DateTime.SpecifyKind(entity.CreateDate, DateTimeKind.Local), + CreateDate = entity.CreateDate, }; return dto; @@ -286,7 +285,7 @@ private static ContentVersionDto BuildContentVersionDto(IContentBase entity, Con { Id = entity.VersionId, NodeId = entity.Id, - VersionDate = DateTime.SpecifyKind(entity.UpdateDate, DateTimeKind.Local), + VersionDate = entity.UpdateDate, UserId = entity.WriterId, Current = true, // always building the current one Text = entity.Name, diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/ContentTypeFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/ContentTypeFactory.cs index 02d7c6be084a..0c78a9a84c77 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/ContentTypeFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/ContentTypeFactory.cs @@ -1,5 +1,6 @@ using System.Globalization; using Umbraco.Cms.Core; +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Entities; using Umbraco.Cms.Core.Strings; @@ -149,8 +150,8 @@ private static void BuildCommonEntity(ContentTypeBase entity, ContentTypeDto dto entity.Thumbnail = dto.Thumbnail; entity.SortOrder = dto.NodeDto.SortOrder; entity.Description = dto.Description; - entity.CreateDate = dto.NodeDto.CreateDate; - entity.UpdateDate = dto.NodeDto.CreateDate; + entity.CreateDate = dto.NodeDto.CreateDate.EnsureUtc(); + entity.UpdateDate = dto.NodeDto.CreateDate.EnsureUtc(); entity.Path = dto.NodeDto.Path; entity.Level = dto.NodeDto.Level; entity.CreatorId = dto.NodeDto.UserId ?? Constants.Security.UnknownUserId; diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/DataTypeFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/DataTypeFactory.cs index e4509ee095c2..68c6a4094652 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/DataTypeFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/DataTypeFactory.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Logging; using Umbraco.Cms.Core; +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Serialization; @@ -29,12 +30,12 @@ public static IDataType BuildEntity(DataTypeDto dto, PropertyEditorCollection ed { dataType.DisableChangeTracking(); - dataType.CreateDate = dto.NodeDto.CreateDate; + dataType.CreateDate = dto.NodeDto.CreateDate.EnsureUtc(); dataType.DatabaseType = dto.DbType.EnumParse(true); dataType.Id = dto.NodeId; dataType.Key = dto.NodeDto.UniqueId; dataType.Level = dto.NodeDto.Level; - dataType.UpdateDate = dto.NodeDto.CreateDate; + dataType.UpdateDate = dto.NodeDto.CreateDate.EnsureUtc(); dataType.Name = dto.NodeDto.Text; dataType.ParentId = dto.NodeDto.ParentId; dataType.Path = dto.NodeDto.Path; diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/ExternalLoginFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/ExternalLoginFactory.cs index 77ab4ed404f7..c1c2b74be813 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/ExternalLoginFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/ExternalLoginFactory.cs @@ -1,3 +1,4 @@ +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Security; using Umbraco.Cms.Infrastructure.Persistence.Dtos; using Umbraco.Extensions; @@ -8,7 +9,7 @@ internal static class ExternalLoginFactory { public static IIdentityUserToken BuildEntity(ExternalLoginTokenDto dto) { - var entity = new IdentityUserToken(dto.Id, dto.ExternalLoginDto.LoginProvider, dto.Name, dto.Value, dto.ExternalLoginDto.UserOrMemberKey.ToString(), dto.CreateDate); + var entity = new IdentityUserToken(dto.Id, dto.ExternalLoginDto.LoginProvider, dto.Name, dto.Value, dto.ExternalLoginDto.UserOrMemberKey.ToString(), dto.CreateDate.EnsureUtc()); // reset dirty initial properties (U4-1946) entity.ResetDirtyProperties(false); @@ -22,7 +23,7 @@ public static IIdentityUserLogin BuildEntity(ExternalLoginDto dto) var key = dto.UserId.HasValue ? dto.UserId.Value.ToGuid().ToString() : dto.UserOrMemberKey.ToString(); var entity = - new IdentityUserLogin(dto.Id, dto.LoginProvider, dto.ProviderKey, key, dto.CreateDate) + new IdentityUserLogin(dto.Id, dto.LoginProvider, dto.ProviderKey, key, dto.CreateDate.EnsureUtc()) { UserData = dto.UserData, }; @@ -56,7 +57,7 @@ public static ExternalLoginDto BuildDto(Guid userOrMemberKey, IExternalLogin ent LoginProvider = entity.LoginProvider, ProviderKey = entity.ProviderKey, UserData = entity.UserData, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }; return dto; @@ -70,7 +71,7 @@ public static ExternalLoginTokenDto BuildDto(int externalLoginId, IExternalLogin ExternalLoginId = externalLoginId, Name = token.Name, Value = token.Value, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, }; return dto; diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/MemberGroupFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/MemberGroupFactory.cs index b6ecbe3b6f11..8351b68960ca 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/MemberGroupFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/MemberGroupFactory.cs @@ -1,4 +1,5 @@ using Umbraco.Cms.Core; +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Infrastructure.Persistence.Dtos; @@ -20,7 +21,7 @@ public static IMemberGroup BuildEntity(NodeDto dto) { group.DisableChangeTracking(); - group.CreateDate = dto.CreateDate; + group.CreateDate = dto.CreateDate.EnsureUtc(); group.Id = dto.NodeId; group.Key = dto.UniqueId; group.Name = dto.Text; diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/PropertyGroupFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/PropertyGroupFactory.cs index 65dc528c172b..f0ff5246660f 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/PropertyGroupFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/PropertyGroupFactory.cs @@ -1,4 +1,5 @@ -using Umbraco.Cms.Core.Models; +using Umbraco.Cms.Core.Extensions; +using Umbraco.Cms.Core.Models; using Umbraco.Cms.Infrastructure.Persistence.Dtos; using Umbraco.Extensions; @@ -129,8 +130,8 @@ public static IEnumerable BuildEntity( propertyType.ValidationRegExp = typeDto.ValidationRegExp; propertyType.ValidationRegExpMessage = typeDto.ValidationRegExpMessage; propertyType.PropertyGroupId = new Lazy(() => tempGroupDto.Id); - propertyType.CreateDate = createDate; - propertyType.UpdateDate = updateDate; + propertyType.CreateDate = createDate.EnsureUtc(); + propertyType.UpdateDate = updateDate.EnsureUtc(); propertyType.Variations = (ContentVariation)typeDto.Variations; // reset dirty initial properties (U4-1946) diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/PublicAccessEntryFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/PublicAccessEntryFactory.cs index 25232b4f9f9b..1394ae92d499 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/PublicAccessEntryFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/PublicAccessEntryFactory.cs @@ -1,3 +1,4 @@ +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Infrastructure.Persistence.Dtos; @@ -16,10 +17,10 @@ public static PublicAccessEntry BuildEntity(AccessDto dto) { RuleValue = x.RuleValue, RuleType = x.RuleType, - CreateDate = x.CreateDate, - UpdateDate = x.UpdateDate, + CreateDate = x.CreateDate.EnsureUtc(), + UpdateDate = x.UpdateDate.EnsureUtc(), })) - { CreateDate = dto.CreateDate, UpdateDate = dto.UpdateDate }; + { CreateDate = dto.CreateDate.EnsureUtc(), UpdateDate = dto.UpdateDate.EnsureUtc() }; // reset dirty initial properties (U4-1946) entity.ResetDirtyProperties(false); diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/RelationFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/RelationFactory.cs index 872810ddd67e..455057d1fe60 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/RelationFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/RelationFactory.cs @@ -1,3 +1,4 @@ +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Infrastructure.Persistence.Dtos; @@ -14,9 +15,9 @@ public static IRelation BuildEntity(RelationDto dto, IRelationType relationType) entity.DisableChangeTracking(); entity.Comment = dto.Comment; - entity.CreateDate = dto.Datetime; + entity.CreateDate = dto.Datetime.EnsureUtc(); entity.Id = dto.Id; - entity.UpdateDate = dto.Datetime; + entity.UpdateDate = dto.Datetime.EnsureUtc(); // reset dirty initial properties (U4-1946) entity.ResetDirtyProperties(false); diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/ServerRegistrationFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/ServerRegistrationFactory.cs index cfbb27bd44b4..fa850b972e0b 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/ServerRegistrationFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/ServerRegistrationFactory.cs @@ -1,3 +1,4 @@ +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Infrastructure.Persistence.Dtos; @@ -7,7 +8,7 @@ internal static class ServerRegistrationFactory { public static ServerRegistration BuildEntity(ServerRegistrationDto dto) { - var model = new ServerRegistration(dto.Id, dto.ServerAddress, dto.ServerIdentity, dto.DateRegistered, dto.DateAccessed, dto.IsActive, dto.IsSchedulingPublisher); + var model = new ServerRegistration(dto.Id, dto.ServerAddress, dto.ServerIdentity, dto.DateRegistered.EnsureUtc(), dto.DateAccessed.EnsureUtc(), dto.IsActive, dto.IsSchedulingPublisher); // reset dirty initial properties (U4-1946) model.ResetDirtyProperties(false); diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/TemplateFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/TemplateFactory.cs index 3028d1a50982..147efbe58e1a 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/TemplateFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/TemplateFactory.cs @@ -1,4 +1,5 @@ -using Umbraco.Cms.Core.Models; +using Umbraco.Cms.Core.Extensions; +using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Entities; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.Persistence.Dtos; @@ -37,7 +38,7 @@ public static Template BuildEntity(IShortStringHelper shortStringHelper, Templat { template.DisableChangeTracking(); - template.CreateDate = dto.NodeDto.CreateDate; + template.CreateDate = dto.NodeDto.CreateDate.EnsureUtc(); template.Id = dto.NodeId; template.Key = dto.NodeDto.UniqueId; template.Path = dto.NodeDto.Path; diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/UserFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/UserFactory.cs index b0172f9341e3..3c556af5e6e6 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/UserFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/UserFactory.cs @@ -1,3 +1,4 @@ +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Models.Membership; using Umbraco.Cms.Core.Models.Membership.Permissions; @@ -40,23 +41,15 @@ public static IUser BuildEntity( user.SecurityStamp = dto.SecurityStampToken; user.FailedPasswordAttempts = dto.FailedLoginAttempts ?? 0; user.Avatar = dto.Avatar; - user.EmailConfirmedDate = dto.EmailConfirmedDate; - user.InvitedDate = dto.InvitedDate; + user.EmailConfirmedDate = dto.EmailConfirmedDate?.EnsureUtc(); + user.InvitedDate = dto.InvitedDate?.EnsureUtc(); user.Kind = (UserKind)dto.Kind; - // Dates stored in the database are local server time, but for SQL Server, will be considered - // as DateTime.Kind = Utc. Fix this so we are consistent when later mapping to DataTimeOffset. - user.LastLockoutDate = dto.LastLockoutDate.HasValue - ? DateTime.SpecifyKind(dto.LastLockoutDate.Value, DateTimeKind.Local) - : null; - user.LastLoginDate = dto.LastLoginDate.HasValue - ? DateTime.SpecifyKind(dto.LastLoginDate.Value, DateTimeKind.Local) - : null; - user.LastPasswordChangeDate = dto.LastPasswordChangeDate.HasValue - ? DateTime.SpecifyKind(dto.LastPasswordChangeDate.Value, DateTimeKind.Local) - : null; - user.CreateDate = DateTime.SpecifyKind(dto.CreateDate, DateTimeKind.Local); - user.UpdateDate = DateTime.SpecifyKind(dto.UpdateDate, DateTimeKind.Local); + user.LastLockoutDate = dto.LastLockoutDate?.EnsureUtc(); + user.LastLoginDate = dto.LastLoginDate?.EnsureUtc(); + user.LastPasswordChangeDate = dto.LastPasswordChangeDate?.EnsureUtc(); + user.CreateDate = dto.CreateDate.EnsureUtc(); + user.UpdateDate = dto.UpdateDate.EnsureUtc(); // reset dirty initial properties (U4-1946) user.ResetDirtyProperties(false); diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/UserGroupFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/UserGroupFactory.cs index 5cc65e6a014c..cf12fe463008 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/UserGroupFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/UserGroupFactory.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models.Membership; using Umbraco.Cms.Core.Models.Membership.Permissions; using Umbraco.Cms.Core.Strings; @@ -24,8 +24,8 @@ public static IUserGroup BuildEntity(IShortStringHelper shortStringHelper, UserG userGroup.DisableChangeTracking(); userGroup.Id = dto.Id; userGroup.Key = dto.Key; - userGroup.CreateDate = dto.CreateDate; - userGroup.UpdateDate = dto.UpdateDate; + userGroup.CreateDate = dto.CreateDate.EnsureUtc(); + userGroup.UpdateDate = dto.UpdateDate.EnsureUtc(); userGroup.StartContentId = dto.StartContentId; userGroup.StartMediaId = dto.StartMediaId; userGroup.Permissions = dto.UserGroup2PermissionDtos.Select(x => x.Permission).ToHashSet(); diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/WebhookLogFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/WebhookLogFactory.cs index 886ee58eaf93..2202dec6d137 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/WebhookLogFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/WebhookLogFactory.cs @@ -1,6 +1,6 @@ using System.Text.RegularExpressions; +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Webhooks; using Umbraco.Cms.Infrastructure.Persistence.Dtos; namespace Umbraco.Cms.Infrastructure.Persistence.Factories; @@ -28,7 +28,7 @@ public static WebhookLogDto CreateDto(WebhookLog log) => public static WebhookLog DtoToEntity(WebhookLogDto dto) => new() { - Date = dto.Date, + Date = dto.Date.EnsureUtc(), EventAlias = dto.EventAlias, RequestBody = dto.RequestBody, ResponseBody = dto.ResponseBody, diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/WebhookRequestFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/WebhookRequestFactory.cs index dd0648588b15..685fce5be093 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/WebhookRequestFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/WebhookRequestFactory.cs @@ -1,4 +1,4 @@ -using Umbraco.Cms.Core.Models; +using Umbraco.Cms.Core.Models; using Umbraco.Cms.Infrastructure.Persistence.Dtos; namespace Umbraco.Cms.Infrastructure.Persistence.Factories; diff --git a/src/Umbraco.Infrastructure/Persistence/Mappers/AuditEntryMapper.cs b/src/Umbraco.Infrastructure/Persistence/Mappers/AuditEntryMapper.cs index 04fc3377cd3e..79eb7839553c 100644 --- a/src/Umbraco.Infrastructure/Persistence/Mappers/AuditEntryMapper.cs +++ b/src/Umbraco.Infrastructure/Persistence/Mappers/AuditEntryMapper.cs @@ -22,7 +22,7 @@ protected override void DefineMaps() DefineMap(nameof(AuditEntry.PerformingUserKey), nameof(AuditEntryDto.PerformingUserKey)); DefineMap(nameof(AuditEntry.PerformingDetails), nameof(AuditEntryDto.PerformingDetails)); DefineMap(nameof(AuditEntry.PerformingIp), nameof(AuditEntryDto.PerformingIp)); - DefineMap(nameof(AuditEntry.EventDateUtc), nameof(AuditEntryDto.EventDateUtc)); + DefineMap(nameof(AuditEntry.EventDate), nameof(AuditEntryDto.EventDate)); DefineMap(nameof(AuditEntry.AffectedUserId), nameof(AuditEntryDto.AffectedUserId)); DefineMap(nameof(AuditEntry.AffectedUserKey), nameof(AuditEntryDto.AffectedUserKey)); DefineMap(nameof(AuditEntry.AffectedDetails), nameof(AuditEntryDto.AffectedDetails)); diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/AuditEntryRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/AuditEntryRepository.cs index 242f3151f754..1fa6d9e52359 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/AuditEntryRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/AuditEntryRepository.cs @@ -42,7 +42,7 @@ public IEnumerable GetPage(long pageIndex, int pageCount, out long Sql sql = Sql() .Select() .From() - .OrderByDescending(x => x.EventDateUtc); + .OrderByDescending(x => x.EventDate); Page page = Database.Page(pageIndex + 1, pageCount, sql); records = page.TotalItems; @@ -133,7 +133,7 @@ protected override void PersistNewItem(IAuditEntry entity) x => x.PerformingUserId, x => x.PerformingDetails, x => x.PerformingIp, - x => x.EventDateUtc, + x => x.EventDate, x => x.AffectedUserId, x => x.AffectedDetails, x => x.EventType, diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/AuditRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/AuditRepository.cs index 35aa2208802a..9ccaa4960ced 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/AuditRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/AuditRepository.cs @@ -6,6 +6,7 @@ using Umbraco.Cms.Core.Persistence.Querying; using Umbraco.Cms.Core.Persistence.Repositories; using Umbraco.Cms.Infrastructure.Persistence.Dtos; +using Umbraco.Cms.Infrastructure.Persistence.Factories; using Umbraco.Cms.Infrastructure.Persistence.Querying; using Umbraco.Cms.Infrastructure.Scoping; using Umbraco.Extensions; @@ -29,12 +30,12 @@ public IEnumerable Get(AuditType type, IQuery query) List? dtos = Database.Fetch(sql); - return dtos.Select(x => new AuditItem(x.NodeId, Enum.Parse(x.Header), x.UserId ?? Constants.Security.UnknownUserId, x.EntityType, x.Comment, x.Parameters, DateTime.SpecifyKind(x.Datestamp, DateTimeKind.Local))).ToList(); + return AuditItemFactory.BuildEntities(dtos); } public void CleanLogs(int maximumAgeOfLogsInMinutes) { - DateTime oldestPermittedLogEntry = DateTime.Now.Subtract(new TimeSpan(0, maximumAgeOfLogsInMinutes, 0)); + DateTime oldestPermittedLogEntry = DateTime.UtcNow.Subtract(new TimeSpan(0, maximumAgeOfLogsInMinutes, 0)); Database.Execute( "delete from umbracoLog where datestamp < @oldestPermittedLogEntry and logHeader in ('open','system')", @@ -103,43 +104,16 @@ public IEnumerable GetPagedResultsByQuery( Page? page = Database.Page(pageIndex + 1, pageSize, sql); totalRecords = page.TotalItems; - var items = page.Items.Select( - dto => new AuditItem(dto.NodeId, Enum.ParseOrNull(dto.Header) ?? AuditType.Custom, dto.UserId ?? Constants.Security.UnknownUserId, dto.EntityType, dto.Comment, dto.Parameters, DateTime.SpecifyKind(dto.Datestamp, DateTimeKind.Local))).ToList(); - - // map the DateStamp - for (var i = 0; i < items.Count; i++) - { - items[i].CreateDate = DateTime.SpecifyKind(page.Items[i].Datestamp, DateTimeKind.Local); - } - - return items; + return AuditItemFactory.BuildEntities(page.Items); } protected override void PersistNewItem(IAuditItem entity) => - Database.Insert(new LogDto - { - Comment = entity.Comment, - Datestamp = DateTime.Now, - Header = entity.AuditType.ToString(), - NodeId = entity.Id, - UserId = entity.UserId, - EntityType = entity.EntityType, - Parameters = entity.Parameters, - }); + Database.Insert(AuditItemFactory.BuildDto(entity)); protected override void PersistUpdatedItem(IAuditItem entity) => // inserting when updating because we never update a log entry, perhaps this should throw? - Database.Insert(new LogDto - { - Comment = entity.Comment, - Datestamp = DateTime.Now, - Header = entity.AuditType.ToString(), - NodeId = entity.Id, - UserId = entity.UserId, - EntityType = entity.EntityType, - Parameters = entity.Parameters, - }); + Database.Insert(AuditItemFactory.BuildDto(entity)); protected override IAuditItem? PerformGet(int id) { @@ -149,7 +123,7 @@ protected override void PersistUpdatedItem(IAuditItem entity) => LogDto? dto = Database.First(sql); return dto == null ? null - : new AuditItem(dto.NodeId, Enum.Parse(dto.Header), dto.UserId ?? Constants.Security.UnknownUserId, dto.EntityType, dto.Comment, dto.Parameters, DateTime.SpecifyKind(dto.Datestamp, DateTimeKind.Local)); + : AuditItemFactory.BuildEntity(dto); } protected override IEnumerable PerformGetAll(params int[]? ids) => throw new NotImplementedException(); @@ -162,7 +136,7 @@ protected override IEnumerable PerformGetByQuery(IQuery List? dtos = Database.Fetch(sql); - return dtos.Select(x => new AuditItem(x.NodeId, Enum.Parse(x.Header), x.UserId ?? Constants.Security.UnknownUserId, x.EntityType, x.Comment, x.Parameters, DateTime.SpecifyKind(x.Datestamp, DateTimeKind.Local))).ToList(); + return AuditItemFactory.BuildEntities(dtos); } protected override Sql GetBaseQuery(bool isCount) diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepository.cs index eece5ab48f06..c6c00eb63710 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeRepository.cs @@ -310,7 +310,7 @@ private void PersistHistoryCleanup(IContentType entity) var dto = new ContentVersionCleanupPolicyDto { ContentTypeId = entity.Id, - Updated = DateTime.Now, + Updated = DateTime.UtcNow, PreventCleanup = entityWithHistoryCleanup.HistoryCleanup?.PreventCleanup ?? false, KeepAllVersionsNewerThanDays = entityWithHistoryCleanup.HistoryCleanup?.KeepAllVersionsNewerThanDays, diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/CreatedPackageSchemaRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/CreatedPackageSchemaRepository.cs index 23556d988223..3fdd664b7805 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/CreatedPackageSchemaRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/CreatedPackageSchemaRepository.cs @@ -194,7 +194,7 @@ public bool SavePackage(PackageDefinition? definition) { Name = definition.Name, Value = _xmlParser.ToXml(definition).ToString(), - UpdateDate = DateTime.Now, + UpdateDate = DateTime.UtcNow, PackageId = Guid.NewGuid(), }; @@ -218,7 +218,7 @@ public bool SavePackage(PackageDefinition? definition) Value = _xmlParser.ToXml(definition).ToString(), Id = definition.Id, PackageId = definition.PackageId, - UpdateDate = DateTime.Now, + UpdateDate = DateTime.UtcNow, }; Database?.Update(updatedDto); diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs index 6dc12aa65824..b58b25f07767 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DataTypeRepository.cs @@ -427,7 +427,7 @@ protected override void PersistDeletedItem(IDataType entity) // Delete (base) node data Database.Delete("WHERE uniqueID = @Id", new { Id = entity.Key }); - entity.DeleteDate = DateTime.Now; + entity.DeleteDate = DateTime.UtcNow; } #endregion diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DictionaryRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DictionaryRepository.cs index b8215b40edcf..473f4495573e 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DictionaryRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DictionaryRepository.cs @@ -428,7 +428,7 @@ protected override void PersistDeletedItem(IDictionaryItem entity) IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.ItemKey)); IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.Key)); - entity.DeleteDate = DateTime.Now; + entity.DeleteDate = DateTime.UtcNow; } private void RecursiveDelete(Guid parentId) diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentRepository.cs index 687a878c83c6..9b086928594b 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentRepository.cs @@ -4,6 +4,7 @@ using Umbraco.Cms.Core; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Events; +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Membership; using Umbraco.Cms.Core.Notifications; @@ -400,17 +401,15 @@ private void SetVariations(Content? content, IDictionary 0 && contentVariations.TryGetValue(content.PublishedVersionId, out contentVariation)) { foreach (ContentVariation v in contentVariation) { - content.SetPublishInfo(v.Culture, v.Name, DateTime.SpecifyKind(v.Date, DateTimeKind.Local)); + content.SetPublishInfo(v.Culture, v.Name, v.Date.EnsureUtc()); } } @@ -1815,7 +1814,7 @@ private void EnsureVariantNamesAreUnique(IContent content, bool publishing) if (publishing && (content.PublishCultureInfos?.ContainsKey(cultureInfo.Culture) ?? false)) { content.SetPublishInfo(cultureInfo.Culture, uniqueName, - DateTime.Now); //TODO: This is weird, this call will have already been made in the SetCultureName + DateTime.UtcNow); //TODO: This is weird, this call will have already been made in the SetCultureName } } } diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentVersionRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentVersionRepository.cs index 2f2ac7b36801..651cd2f743ed 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentVersionRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/DocumentVersionRepository.cs @@ -1,3 +1,4 @@ +using System; using System.Data; using NPoco; using Umbraco.Cms.Core; @@ -48,7 +49,9 @@ public DocumentVersionRepository(IScopeAccessor scopeAccessor) => .Where(x => !x.PreventCleanup) // Never delete "pinned" versions .Where(x => !x.Published); // Never delete published version - return _scopeAccessor.AmbientScope?.Database.Fetch(query); + List? results = _scopeAccessor.AmbientScope?.Database.Fetch(query); + EnsureUtcDates(results); + return results; } /// @@ -99,19 +102,11 @@ public DocumentVersionRepository(IScopeAccessor scopeAccessor) => Page? page = _scopeAccessor.AmbientScope?.Database.Page(pageIndex + 1, pageSize, query); - // Dates stored in the database are local server time, but for SQL Server, will be considered - // as DateTime.Kind = Utc. Fix this so we are consistent when later mapping to DataTimeOffset. - if (page is not null) - { - foreach (ContentVersionMeta item in page.Items) - { - item.SpecifyVersionDateKind(DateTimeKind.Local); - } - } - totalRecords = page?.TotalItems ?? 0; - return page?.Items; + List? results = page?.Items; + EnsureUtcDates(results); + return results; } /// @@ -186,6 +181,16 @@ public void SetPreventCleanup(int versionId, bool preventCleanup) .On(left => left.Id, right => right.UserId) .Where(x => x.Id == versionId); - return _scopeAccessor.AmbientScope?.Database.Single(query); + ContentVersionMeta? result = _scopeAccessor.AmbientScope?.Database.Single(query); + result?.EnsureUtc(); + return result; + } + + private static void EnsureUtcDates(IEnumerable? versions) + { + foreach (ContentVersionMeta version in versions ?? []) + { + version.EnsureUtc(); + } } } diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityContainerRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityContainerRepository.cs index cb1cf56a7226..90d787ad0b32 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityContainerRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityContainerRepository.cs @@ -193,7 +193,7 @@ protected override void PersistDeletedItem(EntityContainer entity) // delete Database.Delete(nodeDto); - entity.DeleteDate = DateTime.Now; + entity.DeleteDate = DateTime.UtcNow; } protected override void PersistNewItem(EntityContainer entity) @@ -247,7 +247,7 @@ protected override void PersistNewItem(EntityContainer entity) // note: sortOrder is NOT managed and always zero for containers nodeDto = new NodeDto { - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, Level = Convert.ToInt16(level + 1), NodeObjectType = entity.ContainerObjectType, ParentId = entity.ParentId, diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepository.cs index c39545f6be74..c0c8d41746c1 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepository.cs @@ -1,6 +1,7 @@ using NPoco; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Cache; +using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Entities; using Umbraco.Cms.Core.Persistence.Querying; @@ -362,7 +363,7 @@ public int ReserveId(Guid key) UniqueId = key, Text = "RESERVED.ID", NodeObjectType = Constants.ObjectTypes.IdReservation, - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, UserId = null, ParentId = -1, Level = 1, @@ -892,8 +893,8 @@ private EntitySlim BuildEntity(BaseDto dto) private static void BuildEntity(EntitySlim entity, BaseDto dto) { entity.Trashed = dto.Trashed; - entity.CreateDate = dto.CreateDate; - entity.UpdateDate = dto.VersionDate; + entity.CreateDate = dto.CreateDate.EnsureUtc(); + entity.UpdateDate = dto.VersionDate.EnsureUtc(); entity.CreatorId = dto.UserId ?? Constants.Security.UnknownUserId; entity.Id = dto.NodeId; entity.Key = dto.UniqueId; diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepositoryBase.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepositoryBase.cs index aeb8f1766e10..78d820a6b23e 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepositoryBase.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/EntityRepositoryBase.cs @@ -243,6 +243,6 @@ protected virtual void PersistDeletedItem(TEntity entity) Database.Execute(delete, new { id = GetEntityId(entity) }); } - entity.DeleteDate = DateTime.Now; + entity.DeleteDate = DateTime.UtcNow; } } diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ServerRegistrationRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ServerRegistrationRepository.cs index 80a19793cf5a..f5b6c43c9163 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ServerRegistrationRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ServerRegistrationRepository.cs @@ -23,7 +23,7 @@ public ServerRegistrationRepository(IScopeAccessor scopeAccessor, ILogger( "SET isActive=0, isSchedulingPublisher=0 WHERE lastNotifiedDate < @timeoutDate", new diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TemplateRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TemplateRepository.cs index f3433a564df5..9de75c7af686 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TemplateRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/TemplateRepository.cs @@ -477,7 +477,7 @@ protected override void PersistUpdatedItem(ITemplate entity) TemplateDto templateDto = Database.SingleOrDefault("WHERE nodeId = @Id", new {entity.Id}); //Save updated entity to db - template.UpdateDate = DateTime.Now; + template.UpdateDate = DateTime.UtcNow; TemplateDto dto = TemplateFactory.BuildDto(template, NodeObjectTypeId, templateDto.PrimaryKey); Database.Update(dto.NodeDto); Database.Update(dto); @@ -551,7 +551,7 @@ protected override void PersistDeletedItem(ITemplate entity) var viewName = string.Concat(entity.Alias, ".cshtml"); _viewsFileSystem?.DeleteFile(viewName); - entity.DeleteDate = DateTime.Now; + entity.DeleteDate = DateTime.UtcNow; } #endregion diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs index 88f9540a4f9e..8f69253526ff 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs @@ -237,9 +237,9 @@ public Guid CreateLoginSession(int? userId, string requestingIpAddress, bool cle { UserId = userId, IpAddress = requestingIpAddress, - LoggedInUtc = now, - LastValidatedUtc = now, - LoggedOutUtc = null, + LoggedIn = now, + LastValidated = now, + LoggedOut = null, SessionId = Guid.NewGuid() }; Database.Insert(dto); @@ -286,13 +286,13 @@ private bool ValidateLoginSessionInternal(int userId, Guid sessionId) Sql sql = t.Sql(sessionId); UserLoginDto? found = Database.FirstOrDefault(sql); - if (found == null || found.UserId != userId || found.LoggedOutUtc.HasValue) + if (found == null || found.UserId != userId || found.LoggedOut.HasValue) { return false; } //now detect if there's been a timeout - if (DateTime.UtcNow - found.LastValidatedUtc > _globalSettings.TimeOut) + if (DateTime.UtcNow - found.LastValidated > _globalSettings.TimeOut) { //timeout detected, update the record if (Logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) @@ -308,7 +308,7 @@ private bool ValidateLoginSessionInternal(int userId, Guid sessionId) { Logger.LogDebug("Updating LastValidatedUtc for sessionId {sessionId}", sessionId); } - found.LastValidatedUtc = DateTime.UtcNow; + found.LastValidated = DateTime.UtcNow; Database.Update(found); return true; } @@ -319,13 +319,13 @@ public int ClearLoginSessions(int userId) => public int ClearLoginSessions(TimeSpan timespan) { DateTime fromDate = DateTime.UtcNow - timespan; - return Database.Delete(Sql().Where(x => x.LastValidatedUtc < fromDate)); + return Database.Delete(Sql().Where(x => x.LastValidated < fromDate)); } public void ClearLoginSession(Guid sessionId) => // TODO: why is that one updating and not deleting? Database.Execute(Sql() - .Update(u => u.Set(x => x.LoggedOutUtc, DateTime.UtcNow)) + .Update(u => u.Set(x => x.LoggedOut, DateTime.UtcNow)) .Where(x => x.SessionId == sessionId)); @@ -677,7 +677,7 @@ protected override void PersistDeletedItem(IUser entity) Database.Execute(delete, new { id = entity.Id, key = GetEntityId(entity) }); } - entity.DeleteDate = DateTime.Now; + entity.DeleteDate = DateTime.UtcNow; } protected override void PersistNewItem(IUser entity) diff --git a/src/Umbraco.Infrastructure/Persistence/SqlSyntax/SqlSyntaxProviderBase.cs b/src/Umbraco.Infrastructure/Persistence/SqlSyntax/SqlSyntaxProviderBase.cs index 089bc23814f9..4b90a4a5a3de 100644 --- a/src/Umbraco.Infrastructure/Persistence/SqlSyntax/SqlSyntaxProviderBase.cs +++ b/src/Umbraco.Infrastructure/Persistence/SqlSyntax/SqlSyntaxProviderBase.cs @@ -611,6 +611,10 @@ protected virtual string FormatDefaultValue(ColumnDefinition column) { column.DefaultValue = SystemMethods.CurrentDateTime; } + else if (string.Equals(column.DefaultValue.ToString(), "GETUTCDATE()", StringComparison.OrdinalIgnoreCase)) + { + column.DefaultValue = SystemMethods.CurrentUTCDateTime; + } // see if this is for a system method if (column.DefaultValue is SystemMethods) diff --git a/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs b/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs index bc955bcb9fa5..6b4fa590e3c5 100644 --- a/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs +++ b/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs @@ -381,7 +381,7 @@ private bool AcquireWhenMaxWaitTimeElapsed(IUmbracoDatabase db) /// Inserts or updates the key/value row /// private RecordPersistenceType InsertLockRecord(string id, IUmbracoDatabase db) => - db.InsertOrUpdate(new KeyValueDto { Key = MainDomKey, Value = id, UpdateDate = DateTime.Now }); + db.InsertOrUpdate(new KeyValueDto { Key = MainDomKey, Value = id, UpdateDate = DateTime.UtcNow }); /// /// Checks if the DB row value is equals the value diff --git a/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs b/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs index c08f12595597..03f8c1eb2e87 100644 --- a/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs +++ b/src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs @@ -18,7 +18,7 @@ public class BackOfficeIdentityUser : UmbracoIdentityUser private string[]? _allowedSections; private string _culture; private IReadOnlyCollection _groups = null!; - private DateTime? _inviteDateUtc; + private DateTime? _inviteDate; private int[] _startContentIds; private int[] _startMediaIds; private UserKind _kind; @@ -49,10 +49,10 @@ private BackOfficeIdentityUser(GlobalSettings globalSettings, IReadOnlyCollectio /// /// Gets or sets invite date /// - public DateTime? InviteDateUtc + public DateTime? InviteDate { - get => _inviteDateUtc; - set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _inviteDateUtc, nameof(InviteDateUtc)); + get => _inviteDate; + set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _inviteDate, nameof(InviteDate)); } /// diff --git a/src/Umbraco.Infrastructure/Security/BackOfficeUserStore.cs b/src/Umbraco.Infrastructure/Security/BackOfficeUserStore.cs index e86d9dfc68f6..93579d0d4eab 100644 --- a/src/Umbraco.Infrastructure/Security/BackOfficeUserStore.cs +++ b/src/Umbraco.Infrastructure/Security/BackOfficeUserStore.cs @@ -775,33 +775,31 @@ private bool UpdateMemberProperties(IUser user, BackOfficeIdentityUser identityU var anythingChanged = false; // don't assign anything if nothing has changed as this will trigger the track changes of the model - if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.LastLoginDateUtc)) - || (user.LastLoginDate != default && identityUser.LastLoginDateUtc.HasValue == false) - || (identityUser.LastLoginDateUtc.HasValue && - user.LastLoginDate?.ToUniversalTime() != identityUser.LastLoginDateUtc.Value)) + if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.LastLoginDate)) + || (user.LastLoginDate != default && identityUser.LastLoginDate.HasValue == false) + || (identityUser.LastLoginDate.HasValue && + user.LastLoginDate?.ToUniversalTime() != identityUser.LastLoginDate.Value)) { anythingChanged = true; - // if the LastLoginDate is being set to MinValue, don't convert it ToLocalTime - DateTime? dt = identityUser.LastLoginDateUtc?.ToLocalTime(); - user.LastLoginDate = dt; + user.LastLoginDate = identityUser.LastLoginDate; } - if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.InviteDateUtc)) - || user.InvitedDate?.ToUniversalTime() != identityUser.InviteDateUtc) + if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.InviteDate)) + || user.InvitedDate?.ToUniversalTime() != identityUser.InviteDate) { anythingChanged = true; - user.InvitedDate = identityUser.InviteDateUtc?.ToLocalTime(); + user.InvitedDate = identityUser.InviteDate; } - if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.LastPasswordChangeDateUtc)) + if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.LastPasswordChangeDate)) || (user.LastPasswordChangeDate.HasValue && user.LastPasswordChangeDate.Value != default && - identityUser.LastPasswordChangeDateUtc.HasValue == false) - || (identityUser.LastPasswordChangeDateUtc.HasValue && user.LastPasswordChangeDate?.ToUniversalTime() != - identityUser.LastPasswordChangeDateUtc.Value)) + identityUser.LastPasswordChangeDate.HasValue == false) + || (identityUser.LastPasswordChangeDate.HasValue && user.LastPasswordChangeDate?.ToUniversalTime() != + identityUser.LastPasswordChangeDate.Value)) { anythingChanged = true; - user.LastPasswordChangeDate = identityUser.LastPasswordChangeDateUtc?.ToLocalTime() ?? DateTime.Now; + user.LastPasswordChangeDate = identityUser.LastPasswordChangeDate ?? DateTime.UtcNow; } if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.EmailConfirmed)) @@ -811,7 +809,7 @@ private bool UpdateMemberProperties(IUser user, BackOfficeIdentityUser identityU identityUser.EmailConfirmed)) { anythingChanged = true; - user.EmailConfirmedDate = identityUser.EmailConfirmed ? DateTime.Now : null; + user.EmailConfirmedDate = identityUser.EmailConfirmed ? DateTime.UtcNow : null; } if (identityUser.IsPropertyDirty(nameof(BackOfficeIdentityUser.Name)) @@ -849,7 +847,7 @@ private bool UpdateMemberProperties(IUser user, BackOfficeIdentityUser identityU if (user.IsLockedOut) { // need to set the last lockout date - user.LastLockoutDate = DateTime.Now; + user.LastLockoutDate = DateTime.UtcNow; } } diff --git a/src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs b/src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs index 5032a2a87182..58607f464380 100644 --- a/src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs +++ b/src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs @@ -80,9 +80,9 @@ private void Map(IUser source, BackOfficeIdentityUser target) target.CalculatedContentStartNodeIds = source.CalculateContentStartNodeIds(_entityService, _appCaches); target.Email = source.Email; target.UserName = source.Username; - target.LastPasswordChangeDateUtc = source.LastPasswordChangeDate?.ToUniversalTime(); - target.LastLoginDateUtc = source.LastLoginDate?.ToUniversalTime(); - target.InviteDateUtc = source.InvitedDate?.ToUniversalTime(); + target.LastPasswordChangeDate = source.LastPasswordChangeDate?.ToUniversalTime(); + target.LastLoginDate = source.LastLoginDate?.ToUniversalTime(); + target.InviteDate = source.InvitedDate?.ToUniversalTime(); target.EmailConfirmed = source.EmailConfirmedDate.HasValue; target.Name = source.Name; target.AccessFailedCount = source.FailedPasswordAttempts; @@ -104,8 +104,8 @@ private void Map(IMember source, MemberIdentityUser target) { target.Email = source.Email; target.UserName = source.Username; - target.LastPasswordChangeDateUtc = source.LastPasswordChangeDate?.ToUniversalTime(); - target.LastLoginDateUtc = source.LastLoginDate?.ToUniversalTime(); + target.LastPasswordChangeDate = source.LastPasswordChangeDate?.ToUniversalTime(); + target.LastLoginDate = source.LastLoginDate?.ToUniversalTime(); target.EmailConfirmed = source.EmailConfirmedDate.HasValue; target.Name = source.Name; target.AccessFailedCount = source.FailedPasswordAttempts; @@ -116,10 +116,10 @@ private void Map(IMember source, MemberIdentityUser target) DateTime? lockedOutUntil = source.LastLockoutDate?.AddMinutes(_securitySettings.MemberDefaultLockoutTimeInMinutes); target.LockoutEnd = source.IsLockedOut ? (lockedOutUntil ?? DateTime.MaxValue).ToUniversalTime() : null; target.Comments = source.Comments; - target.LastLockoutDateUtc = source.LastLockoutDate == DateTime.MinValue + target.LastLockoutDate = source.LastLockoutDate == DateTime.MinValue ? null : source.LastLockoutDate?.ToUniversalTime(); - target.CreatedDateUtc = source.CreateDate.ToUniversalTime(); + target.CreatedDate = source.CreateDate.ToUniversalTime(); target.Key = source.Key; target.MemberTypeAlias = source.ContentTypeAlias; target.TwoFactorEnabled = _twoFactorLoginService.IsTwoFactorEnabledAsync(source.Key).GetAwaiter().GetResult(); diff --git a/src/Umbraco.Infrastructure/Security/MemberIdentityUser.cs b/src/Umbraco.Infrastructure/Security/MemberIdentityUser.cs index a6e779d0b198..8643a7626762 100644 --- a/src/Umbraco.Infrastructure/Security/MemberIdentityUser.cs +++ b/src/Umbraco.Infrastructure/Security/MemberIdentityUser.cs @@ -39,10 +39,10 @@ public string? Comments } // No change tracking because the persisted value is only set with the IsLockedOut flag - public DateTime? LastLockoutDateUtc { get; set; } + public DateTime? LastLockoutDate { get; set; } // No change tracking because the persisted value is readonly - public DateTime CreatedDateUtc { get; set; } + public DateTime CreatedDate { get; set; } // No change tracking because the persisted value is readonly public Guid Key { get; set; } diff --git a/src/Umbraco.Infrastructure/Security/MemberUserStore.cs b/src/Umbraco.Infrastructure/Security/MemberUserStore.cs index a9c293b19c33..3e0113e035cd 100644 --- a/src/Umbraco.Infrastructure/Security/MemberUserStore.cs +++ b/src/Umbraco.Infrastructure/Security/MemberUserStore.cs @@ -245,7 +245,7 @@ public override async Task UpdateAsync( private static bool UpdatingOnlyLoginProperties(IReadOnlyList propertiesUpdated) { - string[] loginPropertyUpdates = [nameof(MemberIdentityUser.LastLoginDateUtc), nameof(MemberIdentityUser.SecurityStamp)]; + string[] loginPropertyUpdates = [nameof(MemberIdentityUser.LastLoginDate), nameof(MemberIdentityUser.SecurityStamp)]; return (propertiesUpdated.Count == 2 && propertiesUpdated.ContainsAll(loginPropertyUpdates)) || (propertiesUpdated.Count == 1 && propertiesUpdated.ContainsAny(loginPropertyUpdates)); } @@ -728,27 +728,23 @@ private IReadOnlyList UpdateMemberProperties(IMember member, MemberIdent updateRoles = false; // don't assign anything if nothing has changed as this will trigger the track changes of the model - if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.LastLoginDateUtc)) - || (member.LastLoginDate != default && identityUser.LastLoginDateUtc.HasValue == false) - || (identityUser.LastLoginDateUtc.HasValue && - member.LastLoginDate?.ToUniversalTime() != identityUser.LastLoginDateUtc.Value)) + if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.LastLoginDate)) + || (member.LastLoginDate != default && identityUser.LastLoginDate.HasValue == false) + || (identityUser.LastLoginDate.HasValue && + member.LastLoginDate?.ToUniversalTime() != identityUser.LastLoginDate.Value)) { - updatedProperties.Add(nameof(MemberIdentityUser.LastLoginDateUtc)); + updatedProperties.Add(nameof(MemberIdentityUser.LastLoginDate)); - // if the LastLoginDate is being set to MinValue, don't convert it ToLocalTime - DateTime dt = identityUser.LastLoginDateUtc == DateTime.MinValue - ? DateTime.MinValue - : identityUser.LastLoginDateUtc?.ToLocalTime() ?? DateTime.MinValue; - member.LastLoginDate = dt; + member.LastLoginDate = identityUser.LastLoginDate; } - if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.LastPasswordChangeDateUtc)) - || (member.LastPasswordChangeDate != default && identityUser.LastPasswordChangeDateUtc.HasValue == false) - || (identityUser.LastPasswordChangeDateUtc.HasValue && member.LastPasswordChangeDate?.ToUniversalTime() != - identityUser.LastPasswordChangeDateUtc.Value)) + if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.LastPasswordChangeDate)) + || (member.LastPasswordChangeDate != default && identityUser.LastPasswordChangeDate.HasValue == false) + || (identityUser.LastPasswordChangeDate.HasValue && member.LastPasswordChangeDate?.ToUniversalTime() != + identityUser.LastPasswordChangeDate.Value)) { - updatedProperties.Add(nameof(MemberIdentityUser.LastPasswordChangeDateUtc)); - member.LastPasswordChangeDate = identityUser.LastPasswordChangeDateUtc?.ToLocalTime() ?? DateTime.Now; + updatedProperties.Add(nameof(MemberIdentityUser.LastPasswordChangeDate)); + member.LastPasswordChangeDate = identityUser.LastPasswordChangeDate ?? DateTime.UtcNow; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Comments)) @@ -765,7 +761,7 @@ private IReadOnlyList UpdateMemberProperties(IMember member, MemberIdent identityUser.EmailConfirmed)) { updatedProperties.Add(nameof(MemberIdentityUser.EmailConfirmed)); - member.EmailConfirmedDate = identityUser.EmailConfirmed ? DateTime.Now : null; + member.EmailConfirmedDate = identityUser.EmailConfirmed ? DateTime.UtcNow : null; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Name)) @@ -797,7 +793,7 @@ private IReadOnlyList UpdateMemberProperties(IMember member, MemberIdent if (member.IsLockedOut) { // need to set the last lockout date - member.LastLockoutDate = DateTime.Now; + member.LastLockoutDate = DateTime.UtcNow; } } diff --git a/src/Umbraco.Infrastructure/Security/UmbracoIdentityUser.cs b/src/Umbraco.Infrastructure/Security/UmbracoIdentityUser.cs index 7a44933e46ce..1bca6b6de5ab 100644 --- a/src/Umbraco.Infrastructure/Security/UmbracoIdentityUser.cs +++ b/src/Umbraco.Infrastructure/Security/UmbracoIdentityUser.cs @@ -76,10 +76,10 @@ public event PropertyChangedEventHandler PropertyChanged /// /// Gets or sets last login date /// - public DateTime? LastLoginDateUtc + public DateTime? LastLoginDate { get => _lastLoginDateUtc; - set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _lastLoginDateUtc, nameof(LastLoginDateUtc)); + set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _lastLoginDateUtc, nameof(LastLoginDate)); } /// @@ -112,11 +112,11 @@ public override string? PasswordHash /// /// Gets or sets dateTime in UTC when the password was last changed. /// - public DateTime? LastPasswordChangeDateUtc + public DateTime? LastPasswordChangeDate { get => _lastPasswordChangeDateUtc; set => BeingDirty.SetPropertyValueAndDetectChanges(value, ref _lastPasswordChangeDateUtc, - nameof(LastPasswordChangeDateUtc)); + nameof(LastPasswordChangeDate)); } /// @@ -260,7 +260,7 @@ public bool IsLockedOut { get { - var isLocked = LockoutEnabled && LockoutEnd.HasValue && LockoutEnd.Value.ToLocalTime() >= DateTime.Now; + var isLocked = LockoutEnabled && LockoutEnd.HasValue && LockoutEnd.Value >= DateTime.UtcNow; return isLocked; } } diff --git a/src/Umbraco.Infrastructure/Security/UmbracoUserStore.cs b/src/Umbraco.Infrastructure/Security/UmbracoUserStore.cs index 1d303f92e9ed..f132ac56c7a3 100644 --- a/src/Umbraco.Infrastructure/Security/UmbracoUserStore.cs +++ b/src/Umbraco.Infrastructure/Security/UmbracoUserStore.cs @@ -245,7 +245,7 @@ public override Task SetNormalizedUserNameAsync(TUser user, string? normalizedNa public override async Task SetPasswordHashAsync(TUser user, string? passwordHash, CancellationToken cancellationToken = default) { await base.SetPasswordHashAsync(user, passwordHash, cancellationToken); - user.LastPasswordChangeDateUtc = DateTime.UtcNow; + user.LastPasswordChangeDate = DateTime.UtcNow; } /// diff --git a/src/Umbraco.PublishedCache.HybridCache/Factories/PublishedContentFactory.cs b/src/Umbraco.PublishedCache.HybridCache/Factories/PublishedContentFactory.cs index 57863dc98698..90c26397e77b 100644 --- a/src/Umbraco.PublishedCache.HybridCache/Factories/PublishedContentFactory.cs +++ b/src/Umbraco.PublishedCache.HybridCache/Factories/PublishedContentFactory.cs @@ -1,4 +1,5 @@ -using Umbraco.Cms.Core.Models; +using Umbraco.Cms.Core.Extensions; +using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; @@ -28,7 +29,7 @@ public PublishedContentFactory( contentCacheNode.Id, contentCacheNode.Key, contentCacheNode.SortOrder, - contentCacheNode.CreateDate, + contentCacheNode.CreateDate.EnsureUtc(), contentCacheNode.CreatorId, contentType, preview ? contentCacheNode.Data : null, @@ -51,7 +52,7 @@ public PublishedContentFactory( contentCacheNode.Id, contentCacheNode.Key, contentCacheNode.SortOrder, - contentCacheNode.CreateDate, + contentCacheNode.CreateDate.EnsureUtc(), contentCacheNode.CreatorId, contentType, null, @@ -64,12 +65,12 @@ public IPublishedMember ToPublishedMember(IMember member) { IPublishedContentType contentType = _publishedContentTypeCache.Get(PublishedItemType.Member, member.ContentTypeId); - // Members are only "mapped" never cached, so these default values are a bit wierd, but they are not used. + // Members are only "mapped" never cached, so these default values are a bit weird, but they are not used. var contentData = new ContentData( member.Name, null, 0, - member.UpdateDate, + member.UpdateDate.EnsureUtc(), member.CreatorId, null, true, @@ -80,7 +81,7 @@ public IPublishedMember ToPublishedMember(IMember member) member.Id, member.Key, member.SortOrder, - member.UpdateDate, + member.UpdateDate.EnsureUtc(), member.CreatorId, contentType, null, diff --git a/src/Umbraco.PublishedCache.HybridCache/PublishedContent.cs b/src/Umbraco.PublishedCache.HybridCache/PublishedContent.cs index 29a865f099aa..0d0f20b124aa 100644 --- a/src/Umbraco.PublishedCache.HybridCache/PublishedContent.cs +++ b/src/Umbraco.PublishedCache.HybridCache/PublishedContent.cs @@ -1,4 +1,4 @@ -using System.Text; +using System.Text; using Microsoft.Extensions.DependencyInjection; using Umbraco.Cms.Core; using Umbraco.Cms.Core.DependencyInjection; @@ -9,6 +9,7 @@ using Umbraco.Cms.Core.Services.Navigation; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Extensions; +using Umbraco.Cms.Core.Extensions; namespace Umbraco.Cms.Infrastructure.HybridCache; @@ -59,11 +60,11 @@ public PublishedContent( Id = contentNode.Id; Key = contentNode.Key; CreatorId = contentNode.CreatorId; - CreateDate = contentNode.CreateDate; + CreateDate = contentNode.CreateDate.EnsureUtc(); SortOrder = contentNode.SortOrder; WriterId = contentData.WriterId; TemplateId = contentData.TemplateId; - UpdateDate = contentData.VersionDate; + UpdateDate = contentData.VersionDate.EnsureUtc(); } public override IPublishedContentType ContentType => _contentNode.ContentType; diff --git a/src/Umbraco.Web.Common/Security/UmbracoSignInManager.cs b/src/Umbraco.Web.Common/Security/UmbracoSignInManager.cs index 1d6d865f9e75..fe6ae29060eb 100644 --- a/src/Umbraco.Web.Common/Security/UmbracoSignInManager.cs +++ b/src/Umbraco.Web.Common/Security/UmbracoSignInManager.cs @@ -351,7 +351,7 @@ protected virtual async Task HandleSignIn(TUser? user, string? use if (result.Succeeded) { // track the last login date - user!.LastLoginDateUtc = DateTime.UtcNow; + user!.LastLoginDate = DateTime.UtcNow; if (user.AccessFailedCount > 0) { // we have successfully logged in, reset the AccessFailedCount diff --git a/src/Umbraco.Web.Website/Models/ProfileModelBuilder.cs b/src/Umbraco.Web.Website/Models/ProfileModelBuilder.cs index 7ca67352c651..8aeab7afc665 100644 --- a/src/Umbraco.Web.Website/Models/ProfileModelBuilder.cs +++ b/src/Umbraco.Web.Website/Models/ProfileModelBuilder.cs @@ -64,10 +64,10 @@ public ProfileModelBuilder WithCustomProperties(bool lookupProperties) Comments = member.Comments, IsApproved = member.IsApproved, IsLockedOut = member.IsLockedOut, - LastLockoutDate = member.LastLockoutDateUtc?.ToLocalTime(), - CreatedDate = member.CreatedDateUtc.ToLocalTime(), - LastLoginDate = member.LastLoginDateUtc?.ToLocalTime(), - LastPasswordChangedDate = member.LastPasswordChangeDateUtc?.ToLocalTime(), + LastLockoutDate = member.LastLockoutDate, + CreatedDate = member.CreatedDate, + LastLoginDate = member.LastLoginDate, + LastPasswordChangedDate = member.LastPasswordChangeDate, RedirectUrl = _redirectUrl, Key = member.Key, }; diff --git a/tests/Umbraco.Tests.Common/Builders/AuditEntryBuilder.cs b/tests/Umbraco.Tests.Common/Builders/AuditEntryBuilder.cs index 3daca9b518a3..b53ac846833b 100644 --- a/tests/Umbraco.Tests.Common/Builders/AuditEntryBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/AuditEntryBuilder.cs @@ -29,7 +29,7 @@ public class AuditEntryBuilder private Guid? _affectedUserKey; private DateTime? _createDate; private DateTime? _deleteDate; - private DateTime? _eventDateUtc; + private DateTime? _eventDate; private string _eventDetails; private string _eventType; private int? _id; @@ -119,7 +119,7 @@ public AuditEntryBuilder WithPerformingIp(string performingIp) public AuditEntryBuilder WithEventDate(DateTime eventDateUtc) { - _eventDateUtc = eventDateUtc; + _eventDate = eventDateUtc; return this; } @@ -139,8 +139,8 @@ public override IAuditEntry Build() { var id = _id ?? 0; var key = _key ?? Guid.NewGuid(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var deleteDate = _deleteDate; var affectedDetails = _affectedDetails ?? Guid.NewGuid().ToString(); var affectedUserId = _affectedUserId ?? -1; @@ -149,7 +149,7 @@ public override IAuditEntry Build() var eventType = _eventType ?? "umbraco/user"; var performingDetails = _performingDetails ?? Guid.NewGuid().ToString(); var performingIp = _performingIp ?? "127.0.0.1"; - var eventDateUtc = _eventDateUtc ?? DateTime.UtcNow; + var eventDate = _eventDate ?? DateTime.UtcNow; var performingUserId = _performingUserId ?? -1; var performingUserKey = _performingUserKey ?? Constants.Security.SuperUserKey; @@ -167,7 +167,7 @@ public override IAuditEntry Build() EventType = eventType, PerformingDetails = performingDetails, PerformingIp = performingIp, - EventDateUtc = eventDateUtc, + EventDate = eventDate, PerformingUserId = performingUserId, PerformingUserKey = performingUserKey, }; diff --git a/tests/Umbraco.Tests.Common/Builders/ContentBuilder.cs b/tests/Umbraco.Tests.Common/Builders/ContentBuilder.cs index 1fd66da31249..2767d26ce3c4 100644 --- a/tests/Umbraco.Tests.Common/Builders/ContentBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/ContentBuilder.cs @@ -226,8 +226,8 @@ public override Content Build() var key = _key ?? Guid.NewGuid(); var parentId = _parentId ?? -1; var parent = _parent; - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var name = _name ?? Guid.NewGuid().ToString(); var creatorId = _creatorId ?? 0; var level = _level ?? 1; diff --git a/tests/Umbraco.Tests.Common/Builders/ContentCultureInfosBuilder.cs b/tests/Umbraco.Tests.Common/Builders/ContentCultureInfosBuilder.cs index 6504ce2d1e20..9892b221ebea 100644 --- a/tests/Umbraco.Tests.Common/Builders/ContentCultureInfosBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/ContentCultureInfosBuilder.cs @@ -28,7 +28,7 @@ public override ContentCultureInfos Build() { var name = Name ?? Guid.NewGuid().ToString(); var cultureIso = _cultureIso ?? "en-us"; - var date = Date ?? DateTime.Now; + var date = Date ?? DateTime.UtcNow; return new ContentCultureInfos(cultureIso) { Name = name, Date = date }; } diff --git a/tests/Umbraco.Tests.Common/Builders/ContentDataBuilder.cs b/tests/Umbraco.Tests.Common/Builders/ContentDataBuilder.cs index e89d68951fbf..f39d6ac32a11 100644 --- a/tests/Umbraco.Tests.Common/Builders/ContentDataBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/ContentDataBuilder.cs @@ -142,7 +142,7 @@ public ContentData Build( { cultureVariation = new CultureVariation { - Date = DateTime.Now, + Date = DateTime.UtcNow, IsDraft = true, Name = _name, UrlSegment = _segment @@ -176,7 +176,7 @@ public ContentData Build( public override ContentData Build() { - var now = _now ?? DateTime.Now; + var now = _now ?? DateTime.UtcNow; var versionId = _versionId ?? 1; var writerId = _writerId ?? -1; var templateId = _templateId ?? 0; @@ -202,13 +202,13 @@ public override ContentData Build() public static ContentData CreateBasic(string name, DateTime? versionDate = null) => new ContentDataBuilder() .WithName(name) - .WithVersionDate(versionDate ?? DateTime.Now) + .WithVersionDate(versionDate ?? DateTime.UtcNow) .Build(); public static ContentData CreateVariant(string name, Dictionary cultureInfos, DateTime? versionDate = null, bool published = true) => new ContentDataBuilder() .WithName(name) - .WithVersionDate(versionDate ?? DateTime.Now) + .WithVersionDate(versionDate ?? DateTime.UtcNow) .WithCultureInfos(cultureInfos) .WithPublished(published) .Build(); diff --git a/tests/Umbraco.Tests.Common/Builders/ContentNodeKitBuilder.cs b/tests/Umbraco.Tests.Common/Builders/ContentNodeKitBuilder.cs deleted file mode 100644 index cbdc89b42eba..000000000000 --- a/tests/Umbraco.Tests.Common/Builders/ContentNodeKitBuilder.cs +++ /dev/null @@ -1,95 +0,0 @@ -// using System; -// using Umbraco.Cms.Infrastructure.HybridCache; -// -// namespace Umbraco.Cms.Tests.Common.Builders; -// -// FIXME: Reintroduce if relevant -// internal class ContentNodeKitBuilder : BuilderBase -// { -// private ContentNode _contentNode; -// private int _contentTypeId; -// private ContentData _draftData; -// private ContentData _publishedData; -// -// public ContentNodeKitBuilder WithContentNode(ContentNode contentNode) -// { -// _contentNode = contentNode; -// return this; -// } -// -// public ContentNodeKitBuilder WithContentNode(int id, Guid uid, int level, string path, int sortOrder, int parentContentId, DateTime createDate, int creatorId) -// { -// _contentNode = new ContentNode(id, uid, level, path, sortOrder, parentContentId, createDate, creatorId); -// return this; -// } -// -// public ContentNodeKitBuilder WithContentTypeId(int contentTypeId) -// { -// _contentTypeId = contentTypeId; -// return this; -// } -// -// public ContentNodeKitBuilder WithDraftData(ContentData draftData) -// { -// _draftData = draftData; -// return this; -// } -// -// public ContentNodeKitBuilder WithPublishedData(ContentData publishedData) -// { -// _publishedData = publishedData; -// return this; -// } -// -// public override ContentNodeKit Build() -// { -// var data = new ContentNodeKit(_contentNode, _contentTypeId, _draftData, _publishedData); -// return data; -// } -// -// /// -// /// Creates a ContentNodeKit -// /// -// /// -// /// -// /// -// /// -// /// -// /// Optional. Will get calculated based on the path value if not specified. -// /// -// /// -// /// Optional. Will get calculated based on the path value if not specified. -// /// -// /// -// /// -// /// -// /// -// /// -// /// -// public static ContentNodeKit CreateWithContent( -// int contentTypeId, -// int id, -// string path, -// int? sortOrder = null, -// int? level = null, -// int? parentContentId = null, -// int creatorId = -1, -// Guid? uid = null, -// DateTime? createDate = null, -// ContentData draftData = null, -// ContentData publishedData = null) -// { -// var pathParts = path.Split(','); -// if (pathParts.Length >= 2) -// { -// parentContentId ??= int.Parse(pathParts[^2]); -// } -// -// return new ContentNodeKitBuilder() -// .WithContentTypeId(contentTypeId) -// .WithContentNode(id, uid ?? Guid.NewGuid(), level ?? pathParts.Length - 1, path, sortOrder ?? 0, parentContentId.Value, createDate ?? DateTime.Now, creatorId) -// .WithDraftData(draftData) -// .WithPublishedData(publishedData) -// .Build(); -// } -// } diff --git a/tests/Umbraco.Tests.Common/Builders/ContentTypeBaseBuilder.cs b/tests/Umbraco.Tests.Common/Builders/ContentTypeBaseBuilder.cs index e01d87aa0eed..41fe7fd6ca5c 100644 --- a/tests/Umbraco.Tests.Common/Builders/ContentTypeBaseBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/ContentTypeBaseBuilder.cs @@ -178,9 +178,9 @@ string IWithThumbnailBuilder.Thumbnail protected Guid GetKey() => _key ?? Guid.NewGuid(); - protected DateTime GetCreateDate() => _createDate ?? DateTime.Now; + protected DateTime GetCreateDate() => _createDate ?? DateTime.UtcNow; - protected DateTime GetUpdateDate() => _updateDate ?? DateTime.Now; + protected DateTime GetUpdateDate() => _updateDate ?? DateTime.UtcNow; protected string GetName() => _name ?? Guid.NewGuid().ToString(); diff --git a/tests/Umbraco.Tests.Common/Builders/DataTypeBuilder.cs b/tests/Umbraco.Tests.Common/Builders/DataTypeBuilder.cs index 284e68592f46..4d0bac267512 100644 --- a/tests/Umbraco.Tests.Common/Builders/DataTypeBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/DataTypeBuilder.cs @@ -129,8 +129,8 @@ public override DataType Build() var parentId = _parentId ?? -1; var id = _id ?? 1; var key = _key ?? Guid.NewGuid(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var deleteDate = _deleteDate; var name = _name ?? Guid.NewGuid().ToString(); var level = _level ?? 0; diff --git a/tests/Umbraco.Tests.Common/Builders/DictionaryItemBuilder.cs b/tests/Umbraco.Tests.Common/Builders/DictionaryItemBuilder.cs index 60d37a6453c2..6ba37e40e39c 100644 --- a/tests/Umbraco.Tests.Common/Builders/DictionaryItemBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/DictionaryItemBuilder.cs @@ -59,8 +59,8 @@ public class DictionaryItemBuilder public override DictionaryItem Build() { - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var deleteDate = _deleteDate; var id = _id ?? 1; var key = _key ?? Guid.NewGuid(); diff --git a/tests/Umbraco.Tests.Common/Builders/DictionaryTranslationBuilder.cs b/tests/Umbraco.Tests.Common/Builders/DictionaryTranslationBuilder.cs index da7523120d06..f1be1a512df6 100644 --- a/tests/Umbraco.Tests.Common/Builders/DictionaryTranslationBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/DictionaryTranslationBuilder.cs @@ -69,8 +69,8 @@ public DictionaryTranslationBuilder WithValue(string value) public override IDictionaryTranslation Build() { - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var deleteDate = _deleteDate; var id = _id ?? 1; var key = _key ?? Guid.NewGuid(); diff --git a/tests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilder.cs b/tests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilder.cs index af5f9c893339..c5f98cdbb438 100644 --- a/tests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilder.cs @@ -130,8 +130,8 @@ public override DocumentEntitySlim Build() { var id = _id ?? 1; var key = _key ?? Guid.NewGuid(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var name = _name ?? Guid.NewGuid().ToString(); var creatorId = _creatorId ?? 1; var level = _level ?? 1; diff --git a/tests/Umbraco.Tests.Common/Builders/LanguageBuilder.cs b/tests/Umbraco.Tests.Common/Builders/LanguageBuilder.cs index 61504bf06965..ae7b6789db89 100644 --- a/tests/Umbraco.Tests.Common/Builders/LanguageBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/LanguageBuilder.cs @@ -106,8 +106,8 @@ public override ILanguage Build() var cultureInfo = _cultureInfo ?? CultureInfo.GetCultureInfo("en-US"); var cultureName = _cultureName ?? cultureInfo.EnglishName; var key = _key ?? Guid.NewGuid(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var deleteDate = _deleteDate; var fallbackLanguageIsoCode = _fallbackLanguageIsoCode; var isDefault = _isDefault ?? false; diff --git a/tests/Umbraco.Tests.Common/Builders/MediaBuilder.cs b/tests/Umbraco.Tests.Common/Builders/MediaBuilder.cs index 12142e0ac6df..70041cee4be2 100644 --- a/tests/Umbraco.Tests.Common/Builders/MediaBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/MediaBuilder.cs @@ -157,8 +157,8 @@ public override Media Build() var id = _id ?? 0; var key = _key ?? Guid.NewGuid(); var parentId = _parentId ?? -1; - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var name = _name ?? Guid.NewGuid().ToString(); var creatorId = _creatorId ?? 0; var level = _level ?? 1; diff --git a/tests/Umbraco.Tests.Common/Builders/MemberBuilder.cs b/tests/Umbraco.Tests.Common/Builders/MemberBuilder.cs index 29eb2f2a3ce7..68d026988084 100644 --- a/tests/Umbraco.Tests.Common/Builders/MemberBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/MemberBuilder.cs @@ -209,8 +209,8 @@ public override Member Build() { var id = _id ?? 0; var key = _key ?? Guid.NewGuid(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var name = _name ?? Guid.NewGuid().ToString(); var creatorId = _creatorId ?? 0; var level = _level ?? 1; @@ -223,9 +223,9 @@ public override Member Build() var failedPasswordAttempts = _failedPasswordAttempts ?? 0; var isApproved = _isApproved ?? false; var isLockedOut = _isLockedOut ?? false; - var lastLockoutDate = _lastLockoutDate ?? DateTime.Now; - var lastLoginDate = _lastLoginDate ?? DateTime.Now; - var lastPasswordChangeDate = _lastPasswordChangeDate ?? DateTime.Now; + var lastLockoutDate = _lastLockoutDate ?? DateTime.UtcNow; + var lastLoginDate = _lastLoginDate ?? DateTime.UtcNow; + var lastPasswordChangeDate = _lastPasswordChangeDate ?? DateTime.UtcNow; var passwordConfig = _passwordConfig ?? "{\"hashAlgorithm\":\"PBKDF2.ASPNETCORE.V3\"}"; if (_memberTypeBuilder is null && _memberType is null) diff --git a/tests/Umbraco.Tests.Common/Builders/MemberGroupBuilder.cs b/tests/Umbraco.Tests.Common/Builders/MemberGroupBuilder.cs index 8bf7db7cc4a8..17407f9bd7a2 100644 --- a/tests/Umbraco.Tests.Common/Builders/MemberGroupBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/MemberGroupBuilder.cs @@ -63,8 +63,8 @@ public override MemberGroup Build() { var id = _id ?? 1; var key = _key ?? Guid.NewGuid(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var name = _name ?? Guid.NewGuid().ToString(); var creatorId = _creatorId ?? 1; diff --git a/tests/Umbraco.Tests.Common/Builders/PropertyBuilder.cs b/tests/Umbraco.Tests.Common/Builders/PropertyBuilder.cs index 477a9fb36f26..c53820b90e2f 100644 --- a/tests/Umbraco.Tests.Common/Builders/PropertyBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/PropertyBuilder.cs @@ -66,8 +66,8 @@ public override IProperty Build() { var id = _id ?? 1; var key = _key ?? Guid.NewGuid(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; if (_propertyTypeBuilder is null && _propertyType is null) { diff --git a/tests/Umbraco.Tests.Common/Builders/PropertyGroupBuilder.cs b/tests/Umbraco.Tests.Common/Builders/PropertyGroupBuilder.cs index 5a958f1389a9..55ce505e8fdf 100644 --- a/tests/Umbraco.Tests.Common/Builders/PropertyGroupBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/PropertyGroupBuilder.cs @@ -116,8 +116,8 @@ public override PropertyGroup Build() { var id = _id ?? 0; var key = _key ?? Guid.NewGuid(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var alias = _alias ?? Guid.NewGuid().ToString(); var name = _name ?? Guid.NewGuid().ToString(); var sortOrder = _sortOrder ?? 0; diff --git a/tests/Umbraco.Tests.Common/Builders/PropertyTypeBuilder.cs b/tests/Umbraco.Tests.Common/Builders/PropertyTypeBuilder.cs index 9b7fce3a9d32..71e14f3641f1 100644 --- a/tests/Umbraco.Tests.Common/Builders/PropertyTypeBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/PropertyTypeBuilder.cs @@ -172,8 +172,8 @@ public override PropertyType Build() var valueStorageType = _valueStorageType ?? ValueStorageType.Nvarchar; var name = _name ?? Guid.NewGuid().ToString(); var alias = _alias ?? name.ToCamelCase(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var sortOrder = _sortOrder ?? 0; var dataTypeId = _dataTypeId ?? -88; var description = _description ?? string.Empty; diff --git a/tests/Umbraco.Tests.Common/Builders/RelationBuilder.cs b/tests/Umbraco.Tests.Common/Builders/RelationBuilder.cs index c21dea4fe6e6..63cfd0f6846e 100644 --- a/tests/Umbraco.Tests.Common/Builders/RelationBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/RelationBuilder.cs @@ -83,8 +83,8 @@ public override Relation Build() var parentId = _parentId ?? 0; var childId = _childId ?? 0; var key = _key ?? Guid.NewGuid(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var comment = _comment ?? string.Empty; if (_relationTypeBuilder == null && _relationType == null) diff --git a/tests/Umbraco.Tests.Common/Builders/RelationTypeBuilder.cs b/tests/Umbraco.Tests.Common/Builders/RelationTypeBuilder.cs index 83cf56e0de93..949bc6cfa3aa 100644 --- a/tests/Umbraco.Tests.Common/Builders/RelationTypeBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/RelationTypeBuilder.cs @@ -115,8 +115,8 @@ public override IRelationTypeWithIsDependency Build() var key = _key ?? Guid.NewGuid(); var isBidirectional = _isBidirectional ?? false; var isDependency = _isDependency ?? false; - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var deleteDate = _deleteDate; return new RelationType(name, alias, isBidirectional, parentObjectType, childObjectType, isDependency) diff --git a/tests/Umbraco.Tests.Common/Builders/TemplateBuilder.cs b/tests/Umbraco.Tests.Common/Builders/TemplateBuilder.cs index 9ee9c9777928..4c87e3ca6436 100644 --- a/tests/Umbraco.Tests.Common/Builders/TemplateBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/TemplateBuilder.cs @@ -103,8 +103,8 @@ public override ITemplate Build() var key = _key ?? Guid.NewGuid(); var name = _name ?? Guid.NewGuid().ToString(); var alias = _alias ?? name.ToCamelCase(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var path = _path ?? $"-1,{id}"; var content = _content; var isMasterTemplate = _isMasterTemplate ?? false; diff --git a/tests/Umbraco.Tests.Common/Builders/UserBuilder.cs b/tests/Umbraco.Tests.Common/Builders/UserBuilder.cs index 741beafd59fc..529b186967bc 100644 --- a/tests/Umbraco.Tests.Common/Builders/UserBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/UserBuilder.cs @@ -216,8 +216,8 @@ public override User Build() var defaultLang = _defaultLang ?? "en"; var globalSettings = new GlobalSettings { DefaultUILanguage = defaultLang }; var key = _key ?? Guid.NewGuid(); - var createDate = _createDate ?? DateTime.Now; - var updateDate = _updateDate ?? DateTime.Now; + var createDate = _createDate ?? DateTime.UtcNow; + var updateDate = _updateDate ?? DateTime.UtcNow; var name = _name ?? "TestUser" + _suffix; var language = _language ?? globalSettings.DefaultUILanguage; var username = _username ?? "TestUser" + _suffix; @@ -226,9 +226,9 @@ public override User Build() var failedPasswordAttempts = _failedPasswordAttempts ?? 0; var isApproved = _isApproved ?? false; var isLockedOut = _isLockedOut ?? false; - var lastLockoutDate = _lastLockoutDate ?? DateTime.Now; - var lastLoginDate = _lastLoginDate ?? DateTime.Now; - var lastPasswordChangeDate = _lastPasswordChangeDate ?? DateTime.Now; + var lastLockoutDate = _lastLockoutDate ?? DateTime.UtcNow; + var lastLoginDate = _lastLoginDate ?? DateTime.UtcNow; + var lastPasswordChangeDate = _lastPasswordChangeDate ?? DateTime.UtcNow; var comments = _comments ?? string.Empty; var sessionTimeout = _sessionTimeout ?? 0; var startContentIds = _startContentIds ?? new[] { -1 }; diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/DeliveryApi/CacheTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/DeliveryApi/CacheTests.cs deleted file mode 100644 index 3bad270d4579..000000000000 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/DeliveryApi/CacheTests.cs +++ /dev/null @@ -1,77 +0,0 @@ -// using Moq; -// using NUnit.Framework; -// using Umbraco.Cms.Core.Cache; -// using Umbraco.Cms.Core.Models.PublishedContent; -// using Umbraco.Cms.Core.PropertyEditors; -// using Umbraco.Cms.Core.PublishedCache; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Infrastructure.PublishedCache.DataSource; -// -// namespace Umbraco.Cms.Tests.Integration.Umbraco.Core.DeliveryApi; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class CacheTests -// { -// [TestCase(PropertyCacheLevel.Snapshot, false, 1)] -// [TestCase(PropertyCacheLevel.Snapshot, true, 1)] -// [TestCase(PropertyCacheLevel.Elements, false, 1)] -// [TestCase(PropertyCacheLevel.Elements, true, 1)] -// [TestCase(PropertyCacheLevel.Element, false, 1)] -// [TestCase(PropertyCacheLevel.Element, true, 1)] -// [TestCase(PropertyCacheLevel.None, false, 4)] -// [TestCase(PropertyCacheLevel.None, true, 4)] -// public void PublishedElementProperty_CachesDeliveryApiValueConversion(PropertyCacheLevel cacheLevel, bool expanding, int expectedConverterHits) -// { -// var contentType = new Mock(); -// contentType.SetupGet(c => c.PropertyTypes).Returns(Array.Empty()); -// -// var contentNode = new ContentNode(123, Guid.NewGuid(), contentType.Object, 1, string.Empty, 1, 1, DateTime.Now, 1); -// var contentData = new ContentData("bla", "bla", 1, DateTime.Now, 1, 1, true, new Dictionary(), null); -// -// var elementCache = new FastDictionaryAppCache(); -// var snapshotCache = new FastDictionaryAppCache(); -// var publishedSnapshotMock = new Mock(); -// publishedSnapshotMock.SetupGet(p => p.ElementsCache).Returns(elementCache); -// publishedSnapshotMock.SetupGet(p => p.SnapshotCache).Returns(snapshotCache); -// -// var publishedSnapshot = publishedSnapshotMock.Object; -// var publishedSnapshotAccessor = new Mock(); -// publishedSnapshotAccessor.Setup(p => p.TryGetPublishedSnapshot(out publishedSnapshot)).Returns(true); -// -// var content = new PublishedContent( -// contentNode, -// contentData, -// publishedSnapshotAccessor.Object, -// Mock.Of(), -// Mock.Of()); -// -// var propertyType = new Mock(); -// var invocationCount = 0; -// propertyType.SetupGet(p => p.CacheLevel).Returns(cacheLevel); -// propertyType.SetupGet(p => p.DeliveryApiCacheLevel).Returns(cacheLevel); -// propertyType.SetupGet(p => p.DeliveryApiCacheLevelForExpansion).Returns(cacheLevel); -// propertyType -// .Setup(p => p.ConvertInterToDeliveryApiObject(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) -// .Returns(() => $"Delivery API value: {++invocationCount}"); -// -// var prop1 = new Property(propertyType.Object, content, publishedSnapshotAccessor.Object); -// var results = new List(); -// results.Add(prop1.GetDeliveryApiValue(expanding)!.ToString()); -// results.Add(prop1.GetDeliveryApiValue(expanding)!.ToString()); -// results.Add(prop1.GetDeliveryApiValue(expanding)!.ToString()); -// results.Add(prop1.GetDeliveryApiValue(expanding)!.ToString()); -// -// Assert.AreEqual("Delivery API value: 1", results.First()); -// Assert.AreEqual(expectedConverterHits, results.Distinct().Count()); -// -// propertyType.Verify( -// p => p.ConvertInterToDeliveryApiObject( -// It.IsAny(), -// It.IsAny(), -// It.IsAny(), -// It.IsAny(), -// It.IsAny()), -// Times.Exactly(expectedConverterHits)); -// } -// } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentServiceTests.cs index 6741ea26e698..0353f86ab279 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/ContentServiceTests.cs @@ -679,7 +679,7 @@ public void Can_Get_Content_For_Expiration() // Act Thread.Sleep(new TimeSpan(0, 0, 0, 2)); - var contents = ContentService.GetContentForExpiration(DateTime.Now).ToList(); + var contents = ContentService.GetContentForExpiration(DateTime.UtcNow).ToList(); // Assert Assert.That(contents, Is.Not.Null); @@ -692,10 +692,10 @@ public void Can_Get_Content_For_Release() { // Arrange // Act - var contents = ContentService.GetContentForRelease(DateTime.Now).ToList(); + var contents = ContentService.GetContentForRelease(DateTime.UtcNow).ToList(); // Assert - Assert.That(DateTime.Now.AddMinutes(-5) <= DateTime.Now); + Assert.That(DateTime.UtcNow.AddMinutes(-5) <= DateTime.UtcNow); Assert.That(contents, Is.Not.Null); Assert.That(contents.Any(), Is.True); Assert.That(contents.Count(), Is.EqualTo(1)); @@ -1289,7 +1289,7 @@ public async Task Can_Publish_And_Unpublish_Cultures_In_Single_Operation() content.SetCultureName("name-fr", langFr.IsoCode); content.SetCultureName("name-da", langDa.IsoCode); - content.PublishCulture(CultureImpact.Explicit(langFr.IsoCode, langFr.IsDefault), DateTime.Now, PropertyEditorCollection); + content.PublishCulture(CultureImpact.Explicit(langFr.IsoCode, langFr.IsDefault), DateTime.UtcNow, PropertyEditorCollection); var result = ContentService.CommitDocumentChanges(content); Assert.IsTrue(result.Success); content = ContentService.GetById(content.Id); @@ -1297,7 +1297,7 @@ public async Task Can_Publish_And_Unpublish_Cultures_In_Single_Operation() Assert.IsFalse(content.IsCulturePublished(langDa.IsoCode)); content.UnpublishCulture(langFr.IsoCode); - content.PublishCulture(CultureImpact.Explicit(langDa.IsoCode, langDa.IsDefault), DateTime.Now, PropertyEditorCollection); + content.PublishCulture(CultureImpact.Explicit(langDa.IsoCode, langDa.IsDefault), DateTime.UtcNow, PropertyEditorCollection); result = ContentService.CommitDocumentChanges(content); Assert.IsTrue(result.Success); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.Delete.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.Delete.cs index d63c803c954c..ca24b4718916 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.Delete.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/UserServiceCrudTests.Delete.cs @@ -33,7 +33,7 @@ public async Task Cannot_Delete_User_With_Login() Assert.IsTrue(creationResult.Success); var createdUser = creationResult.Result.CreatedUser; - createdUser!.LastLoginDate = DateTime.Now; + createdUser!.LastLoginDate = DateTime.UtcNow; userService.Save(createdUser); var result = await userService.DeleteAsync(Constants.Security.SuperUserKey, createdUser.Key); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs index 67483586d2e5..b85d08f443d5 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/NPocoTests/NPocoBulkInsertTests.cs @@ -61,9 +61,9 @@ [id] ASC { ServerAddress = "address" + i, ServerIdentity = "computer" + i, - DateRegistered = DateTime.Now, + DateRegistered = DateTime.UtcNow, IsActive = true, - DateAccessed = DateTime.Now + DateAccessed = DateTime.UtcNow }); } @@ -88,9 +88,9 @@ public void Can_Bulk_Insert_Native_Sql_Bulk_Inserts() { ServerAddress = "address" + i, ServerIdentity = "computer" + i, - DateRegistered = DateTime.Now, + DateRegistered = DateTime.UtcNow, IsActive = true, - DateAccessed = DateTime.Now + DateAccessed = DateTime.UtcNow }); } @@ -121,9 +121,9 @@ public void Can_Bulk_Insert_Native_Sql_Bulk_Inserts_Transaction_Rollback() { ServerAddress = "address" + i, ServerIdentity = "computer" + i, - DateRegistered = DateTime.Now, + DateRegistered = DateTime.UtcNow, IsActive = true, - DateAccessed = DateTime.Now + DateAccessed = DateTime.UtcNow }); } @@ -155,9 +155,9 @@ public void Generate_Bulk_Import_Sql() { ServerAddress = "address" + i, ServerIdentity = "computer" + i, - DateRegistered = DateTime.Now, + DateRegistered = DateTime.UtcNow, IsActive = true, - DateAccessed = DateTime.Now + DateAccessed = DateTime.UtcNow }); } @@ -185,9 +185,9 @@ public void Generate_Bulk_Import_Sql_Exceeding_Max_Params() { ServerAddress = "address" + i, ServerIdentity = "computer" + i, - DateRegistered = DateTime.Now, + DateRegistered = DateTime.UtcNow, IsActive = true, - DateAccessed = DateTime.Now, + DateAccessed = DateTime.UtcNow, IsSchedulingPublisher = true }); } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs index b794eccd867d..b49e9a7cc7e5 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/DocumentRepositoryTest.cs @@ -227,7 +227,7 @@ public void CreateVersions() // publish = new edit version content1.SetValue("title", "title"); - content1.PublishCulture(CultureImpact.Invariant, DateTime.Now, PropertyEditorCollection); + content1.PublishCulture(CultureImpact.Invariant, DateTime.UtcNow, PropertyEditorCollection); content1.PublishedState = PublishedState.Publishing; repository.Save(content1); @@ -303,7 +303,7 @@ public void CreateVersions() new { id = content1.Id })); // publish = version - content1.PublishCulture(CultureImpact.Invariant, DateTime.Now, PropertyEditorCollection); + content1.PublishCulture(CultureImpact.Invariant, DateTime.UtcNow, PropertyEditorCollection); content1.PublishedState = PublishedState.Publishing; repository.Save(content1); @@ -347,7 +347,7 @@ public void CreateVersions() // publish = new version content1.Name = "name-4"; content1.SetValue("title", "title-4"); - content1.PublishCulture(CultureImpact.Invariant, DateTime.Now, PropertyEditorCollection); + content1.PublishCulture(CultureImpact.Invariant, DateTime.UtcNow, PropertyEditorCollection); content1.PublishedState = PublishedState.Publishing; repository.Save(content1); @@ -767,7 +767,7 @@ public void GetAllContentManyVersions() // publish them all foreach (var content in result) { - content.PublishCulture(CultureImpact.Invariant, DateTime.Now, PropertyEditorCollection); + content.PublishCulture(CultureImpact.Invariant, DateTime.UtcNow, PropertyEditorCollection); repository.Save(content); } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs index f860c11c7e05..1a1740d11e5e 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/KeyValueRepositoryTests.cs @@ -25,7 +25,7 @@ public void CanSetAndGet() // Insert new key/value using (var scope = provider.CreateCoreScope()) { - var keyValue = new KeyValue { Identifier = "foo", Value = "bar", UpdateDate = DateTime.Now }; + var keyValue = new KeyValue { Identifier = "foo", Value = "bar", UpdateDate = DateTime.UtcNow }; var repo = CreateRepository(provider); repo.Save(keyValue); scope.Complete(); @@ -47,7 +47,7 @@ public void CanSetAndGet() var repo = CreateRepository(provider); var keyValue = repo.Get("foo"); keyValue.Value = "buzz"; - keyValue.UpdateDate = DateTime.Now; + keyValue.UpdateDate = DateTime.UtcNow; repo.Save(keyValue); scope.Complete(); } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs index 9a491b3a64b8..6088c68af60d 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/NotificationsRepositoryTest.cs @@ -30,7 +30,7 @@ public void CreateNotification() var node = new NodeDto // create bogus item so we can add a notification { - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, @@ -69,8 +69,8 @@ public void GetUserNotifications() Password = "test", UserName = "test", UserLanguage = "en", - CreateDate = DateTime.Now, - UpdateDate = DateTime.Now + CreateDate = DateTime.UtcNow, + UpdateDate = DateTime.UtcNow, }; ScopeAccessor.AmbientScope.Database.Insert(userDto); @@ -81,7 +81,7 @@ public void GetUserNotifications() { var node = new NodeDto { - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, @@ -113,7 +113,7 @@ public void GetEntityNotifications() var node1 = new NodeDto { - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, @@ -128,7 +128,7 @@ public void GetEntityNotifications() var entity1 = Mock.Of(e => e.Id == node1.NodeId); var node2 = new NodeDto { - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, @@ -152,8 +152,8 @@ public void GetEntityNotifications() Password = "test", UserName = "test" + i, UserLanguage = "en", - CreateDate = DateTime.Now, - UpdateDate = DateTime.Now + CreateDate = DateTime.UtcNow, + UpdateDate = DateTime.UtcNow }; ScopeAccessor.AmbientScope.Database.Insert(userDto); var userNew = Mock.Of(e => e.Id == userDto.Id); @@ -176,7 +176,7 @@ public void Delete_By_Entity() var node1 = new NodeDto { - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, @@ -191,7 +191,7 @@ public void Delete_By_Entity() var entity1 = Mock.Of(e => e.Id == node1.NodeId); var node2 = new NodeDto { - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, @@ -215,8 +215,8 @@ public void Delete_By_Entity() Password = "test", UserName = "test" + i, UserLanguage = "en", - CreateDate = DateTime.Now, - UpdateDate = DateTime.Now + CreateDate = DateTime.UtcNow, + UpdateDate = DateTime.UtcNow }; ScopeAccessor.AmbientScope.Database.Insert(userDto); var userNew = Mock.Of(e => e.Id == userDto.Id); @@ -244,8 +244,8 @@ public void Delete_By_User() Password = "test", UserName = "test", UserLanguage = "en", - CreateDate = DateTime.Now, - UpdateDate = DateTime.Now + CreateDate = DateTime.UtcNow, + UpdateDate = DateTime.UtcNow }; ScopeAccessor.AmbientScope.Database.Insert(userDto); @@ -256,7 +256,7 @@ public void Delete_By_User() { var node = new NodeDto { - CreateDate = DateTime.Now, + CreateDate = DateTime.UtcNow, Level = 1, NodeObjectType = Constants.ObjectTypes.ContentItem, ParentId = -1, diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs index 2e23b703ca09..4f089252e95e 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ServerRegistrationRepositoryTest.cs @@ -39,7 +39,7 @@ public void Cannot_Add_Duplicate_Server_Identities() { var repository = CreateRepository(provider); - var server = new ServerRegistration("http://shazwazza.com", "COMPUTER1", DateTime.Now); + var server = new ServerRegistration("http://shazwazza.com", "COMPUTER1", DateTime.UtcNow); Assert.That(() => repository.Save(server), Throws.InstanceOf()); } @@ -156,7 +156,7 @@ public void Can_Perform_Add_On_Repository() var repository = CreateRepository(provider); // Act - var server = new ServerRegistration("http://shazwazza.com", "COMPUTER4", DateTime.Now); + var server = new ServerRegistration("http://shazwazza.com", "COMPUTER4", DateTime.UtcNow); repository.Save(server); // Assert @@ -237,9 +237,9 @@ public void CreateTestData() { var repository = CreateRepository(provider); - repository.Save(new ServerRegistration("http://localhost", "COMPUTER1", DateTime.Now) { IsActive = true }); - repository.Save(new ServerRegistration("http://www.mydomain.com", "COMPUTER2", DateTime.Now)); - repository.Save(new ServerRegistration("https://www.another.domain.com", "Computer3", DateTime.Now)); + repository.Save(new ServerRegistration("http://localhost", "COMPUTER1", DateTime.UtcNow) { IsActive = true }); + repository.Save(new ServerRegistration("http://www.mydomain.com", "COMPUTER2", DateTime.UtcNow)); + repository.Save(new ServerRegistration("https://www.another.domain.com", "Computer3", DateTime.UtcNow)); scope.Complete(); } } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs index 970850449042..d70fc9c191a1 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/TagRepositoryTest.cs @@ -651,12 +651,12 @@ public void Can_Get_Tags_For_Entity_Type_Excluding_Trashed_Entity() ContentTypeRepository.Save(contentType); var content1 = ContentBuilder.CreateSimpleContent(contentType); - content1.PublishCulture(CultureImpact.Invariant, DateTime.Now, GetRequiredService()); + content1.PublishCulture(CultureImpact.Invariant, DateTime.UtcNow, GetRequiredService()); content1.PublishedState = PublishedState.Publishing; DocumentRepository.Save(content1); var content2 = ContentBuilder.CreateSimpleContent(contentType); - content2.PublishCulture(CultureImpact.Invariant, DateTime.Now, GetRequiredService()); + content2.PublishCulture(CultureImpact.Invariant, DateTime.UtcNow, GetRequiredService()); content2.PublishedState = PublishedState.Publishing; content2.Trashed = true; DocumentRepository.Save(content2); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs index b7c8f1ce3c6e..5deacba9931d 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/UserRepositoryTest.cs @@ -425,7 +425,7 @@ public void Validate_Login_Session() // manually update this record to be in the past ScopeAccessor.AmbientScope.Database.Execute(ScopeAccessor.AmbientScope.SqlContext.Sql() - .Update(u => u.Set(x => x.LoggedOutUtc, DateTime.UtcNow.AddDays(-100))) + .Update(u => u.Set(x => x.LoggedOut, DateTime.UtcNow.AddDays(-100))) .Where(x => x.SessionId == sessionId)); var isValid = repository.ValidateLoginSession(user.Id, sessionId); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditEntryServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditEntryServiceTests.cs index db89c9080baa..b1fa189414e9 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditEntryServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/AuditEntryServiceTests.cs @@ -26,7 +26,7 @@ public async Task Write_and_GetAll() expected.PerformingUserKey.Value, expected.PerformingDetails, expected.PerformingIp, - expected.EventDateUtc, + expected.EventDate, expected.AffectedUserKey.Value, expected.AffectedDetails, expected.EventType, @@ -42,7 +42,7 @@ public async Task Write_and_GetAll() Assert.AreEqual(expected.PerformingUserId, actual.PerformingUserId); Assert.AreEqual(expected.PerformingUserKey, actual.PerformingUserKey); Assert.AreEqual(expected.PerformingDetails, actual.PerformingDetails); - Assert.AreEqual(expected.EventDateUtc, actual.EventDateUtc); + Assert.AreEqual(expected.EventDate, actual.EventDate); Assert.AreEqual(expected.AffectedUserId, actual.AffectedUserId); Assert.AreEqual(expected.AffectedUserKey, actual.AffectedUserKey); Assert.AreEqual(expected.AffectedDetails, actual.AffectedDetails); @@ -80,7 +80,7 @@ public async Task Write_and_GetAll_With_Keys() Assert.AreEqual(Constants.Security.SuperUserKey, actual.PerformingUserKey); Assert.AreEqual("performingDetails", actual.PerformingDetails); Assert.AreEqual("performingIp", actual.PerformingIp); - Assert.AreEqual(eventDateUtc, actual.EventDateUtc); + Assert.AreEqual(eventDateUtc, actual.EventDate); Assert.AreEqual(Constants.Security.UnknownUserId, actual.AffectedUserId); Assert.AreEqual(null, actual.AffectedUserKey); Assert.AreEqual("affectedDetails", actual.AffectedDetails); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentVersionCleanupServiceTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentVersionCleanupServiceTest.cs index ac5e9d612853..ec98d5eb21a0 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentVersionCleanupServiceTest.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ContentVersionCleanupServiceTest.cs @@ -60,7 +60,7 @@ public void PerformContentVersionCleanup_WithNoKeepPeriods_DeletesEverythingExce Debug.Assert(before.ContentVersions == 12); // 10 historic + current draft + current published Debug.Assert(before.PropertyData == 12 * 3); // CreateSimpleContentType = 3 props - ContentVersionService.PerformContentVersionCleanup(DateTime.Now.AddHours(1)); + ContentVersionService.PerformContentVersionCleanup(DateTime.UtcNow.AddHours(1)); var after = GetReport(); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs index 70f0d4abbb75..09f2936daa6e 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/ExternalLoginServiceTests.cs @@ -29,8 +29,8 @@ public void Removes_Existing_Duplicates_On_Save() UserService.Save(user); var providerKey = Guid.NewGuid().ToString("N"); - var latest = DateTime.Now.AddDays(-1); - var oldest = DateTime.Now.AddDays(-10); + var latest = DateTime.UtcNow.AddDays(-1); + var oldest = DateTime.UtcNow.AddDays(-10); using (var scope = ScopeProvider.CreateScope()) { diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs index ce382ecf6ce9..5efc9db7efaf 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MemberServiceTests.cs @@ -68,7 +68,7 @@ public void Can_Get_By_Username() [Test] public void Can_Set_Last_Login_Date() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var memberType = MemberTypeService.Get("member"); IMember member = new Member("xname", "xemail", "xusername", "xrawpassword", memberType, true) { @@ -142,7 +142,7 @@ public void Can_Set_Is_Locked_Out() [Test] public void Can_Set_Last_Lockout_Date() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var memberType = MemberTypeService.Get("member"); IMember member = new Member("xname", "xemail", "xusername", "xrawpassword", memberType, true) { LastLockoutDate = now }; @@ -161,7 +161,7 @@ public void Can_Set_Last_Lockout_Date() [Test] public void Can_set_Last_Login_Date() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var memberType = MemberTypeService.Get("member"); IMember member = new Member("xname", "xemail", "xusername", "xrawpassword", memberType, true) { LastLoginDate = now }; @@ -180,7 +180,7 @@ public void Can_set_Last_Login_Date() [Test] public void Can_Set_Last_Password_Change_Date() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var memberType = MemberTypeService.Get("member"); IMember member = new Member("xname", "xemail", "xusername", "xrawpassword", memberType, true) { diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs index cd65b0d35622..42f6d15e69ea 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/RelationServiceTests.cs @@ -226,7 +226,7 @@ public void Update_Bulk_Relations() { var rs = RelationService; - var date = DateTime.Now.AddDays(-10); + var date = DateTime.UtcNow.AddDays(-10); var newRelations = CreateRelations(10); foreach (var r in newRelations) { @@ -238,7 +238,7 @@ public void Update_Bulk_Relations() RelationService.Save(newRelations); Assert.IsTrue(newRelations.All(x => x.UpdateDate == date)); - var newDate = DateTime.Now.AddDays(-5); + var newDate = DateTime.UtcNow.AddDays(-5); foreach (var r in newRelations) { r.UpdateDate = newDate; diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs index d5ef54ece64c..e0a87857d2a6 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/UserServiceTests.cs @@ -725,7 +725,7 @@ public void Count_All_Users() public void Count_All_Online_Users() { var users = UserBuilder.CreateMulipleUsers(10, - (i, member) => member.LastLoginDate = DateTime.Now.AddMinutes(i * -2)); + (i, member) => member.LastLoginDate = DateTime.UtcNow.AddMinutes(i * -2)); UserService.Save(users); var customUser = UserBuilder.CreateUser(); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RuntimeAppCacheTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RuntimeAppCacheTests.cs index b018434b4308..e95f90aec71a 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RuntimeAppCacheTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/RuntimeAppCacheTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Umbraco. // See LICENSE for more details. -using System.Threading; using NUnit.Framework; using Umbraco.Cms.Core.Cache; using Umbraco.Extensions; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/SystemDateMigrationSettingsValidatorTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/SystemDateMigrationSettingsValidatorTests.cs new file mode 100644 index 000000000000..23565db4f150 --- /dev/null +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Configuration/Models/Validation/SystemDateMigrationSettingsValidatorTests.cs @@ -0,0 +1,47 @@ +// Copyright (c) Umbraco. +// See LICENSE for more details. + +using Microsoft.Extensions.Options; +using NUnit.Framework; +using Umbraco.Cms.Core.Configuration.Models; +using Umbraco.Cms.Core.Configuration.Models.Validation; + +namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Configuration.Models.Validation +{ + [TestFixture] + public class SystemDateMigrationSettingsValidatorTests + { + [Test] + public void Returns_Success_For_Empty_Configuration() + { + var validator = new SystemDateMigrationSettingsValidator(); + SystemDateMigrationSettings options = BuildSystemDateMigrationSettings(); + ValidateOptionsResult result = validator.Validate("settings", options); + Assert.True(result.Succeeded); + } + + [Test] + public void Returns_Success_For_Valid_Configuration() + { + var validator = new SystemDateMigrationSettingsValidator(); + SystemDateMigrationSettings options = BuildSystemDateMigrationSettings(localServerTimeZone: "Central European Standard Time"); + ValidateOptionsResult result = validator.Validate("settings", options); + Assert.True(result.Succeeded); + } + + [Test] + public void Returns_Fail_For_Configuration_With_Invalid_LocalServerTimeZone() + { + var validator = new SystemDateMigrationSettingsValidator(); + SystemDateMigrationSettings options = BuildSystemDateMigrationSettings(localServerTimeZone: "Invalid Time Zone"); + ValidateOptionsResult result = validator.Validate("settings", options); + Assert.False(result.Succeeded); + } + + private static SystemDateMigrationSettings BuildSystemDateMigrationSettings(string? localServerTimeZone = null) => + new SystemDateMigrationSettings + { + LocalServerTimeZone = localServerTimeZone, + }; + } +} diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/ContentRouteBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/ContentRouteBuilderTests.cs index 03da8c6989a8..baa7f8187590 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/ContentRouteBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/ContentRouteBuilderTests.cs @@ -1,4 +1,4 @@ -using Microsoft.Extensions.Options; +using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; using Umbraco.Cms.Core; @@ -398,7 +398,7 @@ private IPublishedContent SetupVariantPublishedContent(string name, Guid key, Mo .SetupGet(m => m.Cultures) .Returns(cultures.ToDictionary( c => c, - c => new PublishedCultureInfo(c, $"{name}-{c}", DefaultUrlSegment(name, c), DateTime.Now))); + c => new PublishedCultureInfo(c, $"{name}-{c}", DefaultUrlSegment(name, c), DateTime.UtcNow))); return content.Object; } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/DeliveryApiTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/DeliveryApiTests.cs index c165666cc35c..1af6c306f35e 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/DeliveryApiTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/DeliveryApi/DeliveryApiTests.cs @@ -119,7 +119,7 @@ protected void ConfigurePublishedContentMock(Mock content, Gu { { string.Empty, - new PublishedCultureInfo(string.Empty, name, urlSegment, DateTime.Now) + new PublishedCultureInfo(string.Empty, name, urlSegment, DateTime.UtcNow) } }); content.SetupGet(c => c.ContentType).Returns(contentType); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs index 443dea94d5c7..0186ae353a65 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/Collections/Item.cs @@ -212,14 +212,14 @@ protected virtual void OnPropertyChanged(PropertyInfo propertyInfo) /// internal virtual void AddingEntity() { - CreateDate = DateTime.Now; - UpdateDate = DateTime.Now; + CreateDate = DateTime.UtcNow; + UpdateDate = DateTime.UtcNow; } /// /// Method to call on entity saved/updated /// - internal virtual void UpdatingEntity() => UpdateDate = DateTime.Now; + internal virtual void UpdatingEntity() => UpdateDate = DateTime.UtcNow; public static bool operator ==(Item left, Item right) => ReferenceEquals(left, right); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentExtensionsTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentExtensionsTests.cs index 45630777f055..56cc4b5ae9cc 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentExtensionsTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentExtensionsTests.cs @@ -101,7 +101,7 @@ public void DirtyProperty_UpdateDate() Assert.IsFalse(content.IsEntityDirty()); Assert.AreEqual(d, content.UpdateDate); - content.UpdateDate = DateTime.Now; + content.UpdateDate = DateTime.UtcNow; Assert.IsTrue(content.IsEntityDirty()); Assert.AreNotEqual(d, content.UpdateDate); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentScheduleTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentScheduleTests.cs index a6958ae9309c..3df13bb165b0 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentScheduleTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentScheduleTests.cs @@ -14,7 +14,7 @@ public class ContentScheduleTests [Test] public void Release_Date_Less_Than_Expire_Date() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var schedule = new ContentScheduleCollection(); Assert.IsFalse(schedule.Add(now, now)); } @@ -22,7 +22,7 @@ public void Release_Date_Less_Than_Expire_Date() [Test] public void Cannot_Add_Duplicate_Dates_Invariant() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var schedule = new ContentScheduleCollection(); schedule.Add(now, null); Assert.Throws(() => schedule.Add(null, now)); @@ -31,7 +31,7 @@ public void Cannot_Add_Duplicate_Dates_Invariant() [Test] public void Cannot_Add_Duplicate_Dates_Variant() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var schedule = new ContentScheduleCollection(); schedule.Add(now, null); schedule.Add("en-US", now, null); @@ -42,7 +42,7 @@ public void Cannot_Add_Duplicate_Dates_Variant() [Test] public void Can_Remove_Invariant() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var schedule = new ContentScheduleCollection(); schedule.Add(now, null); var invariantSched = schedule.GetSchedule(Constants.System.InvariantCulture); @@ -53,7 +53,7 @@ public void Can_Remove_Invariant() [Test] public void Can_Remove_Variant() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var schedule = new ContentScheduleCollection(); schedule.Add(now, null); schedule.Add("en-US", now, null); @@ -70,7 +70,7 @@ public void Can_Remove_Variant() [Test] public void Can_Clear_Start_Invariant() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var schedule = new ContentScheduleCollection(); schedule.Add(now, now.AddDays(1)); @@ -84,7 +84,7 @@ public void Can_Clear_Start_Invariant() [Test] public void Can_Clear_End_Variant() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var schedule = new ContentScheduleCollection(); schedule.Add(now, now.AddDays(1)); schedule.Add("en-US", now, now.AddDays(1)); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTests.cs index c7bb0b07c5fb..40060e39f11d 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/ContentTests.cs @@ -94,7 +94,7 @@ public void Variant_Published_Culture_Names_Track_Dirty_Changes() Thread.Sleep(500); // The "Date" wont be dirty if the test runs too fast since it will be the same date content.SetCultureName("name-fr", langFr); - content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.Now, _propertyEditorCollection); // we've set the name, now we're publishing it + content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.UtcNow, _propertyEditorCollection); // we've set the name, now we're publishing it Assert.IsTrue( content.IsPropertyDirty("PublishCultureInfos")); // now it will be changed since the collection has changed var frCultureName = content.PublishCultureInfos[langFr]; @@ -108,7 +108,7 @@ public void Variant_Published_Culture_Names_Track_Dirty_Changes() Thread.Sleep(500); // The "Date" wont be dirty if the test runs too fast since it will be the same date content.SetCultureName("name-fr", langFr); - content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.Now, _propertyEditorCollection); // we've set the name, now we're publishing it + content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.UtcNow, _propertyEditorCollection); // we've set the name, now we're publishing it Assert.IsTrue(frCultureName.IsPropertyDirty("Date")); Assert.IsTrue(content.IsPropertyDirty("PublishCultureInfos")); // it's true now since we've updated a name } @@ -261,7 +261,7 @@ public void Can_Deep_Clone_Perf_Test() } content.Id = 10; - content.CreateDate = DateTime.Now; + content.CreateDate = DateTime.UtcNow; content.CreatorId = 22; content.Key = Guid.NewGuid(); content.Level = 3; @@ -269,7 +269,7 @@ public void Can_Deep_Clone_Perf_Test() content.SortOrder = 5; content.TemplateId = 88; content.Trashed = false; - content.UpdateDate = DateTime.Now; + content.UpdateDate = DateTime.UtcNow; content.WriterId = 23; var runtimeCache = new ObjectCacheAppCache(); @@ -308,7 +308,7 @@ public void Can_Deep_Clone() content.SetCultureName("Hello", "en-US"); content.SetCultureName("World", "es-ES"); - content.PublishCulture(CultureImpact.All, DateTime.Now, _propertyEditorCollection); + content.PublishCulture(CultureImpact.All, DateTime.UtcNow, _propertyEditorCollection); // should not try to clone something that's not Published or Unpublished // (and in fact it will not work) @@ -323,7 +323,7 @@ public void Can_Deep_Clone() } content.Id = 10; - content.CreateDate = DateTime.Now; + content.CreateDate = DateTime.UtcNow; content.CreatorId = 22; content.Key = Guid.NewGuid(); content.Level = 3; @@ -331,7 +331,7 @@ public void Can_Deep_Clone() content.SortOrder = 5; content.TemplateId = 88; content.Trashed = false; - content.UpdateDate = DateTime.Now; + content.UpdateDate = DateTime.UtcNow; content.WriterId = 23; // Act @@ -421,7 +421,7 @@ public void Remember_Dirty_Properties() content.SetCultureName("Hello", "en-US"); content.SetCultureName("World", "es-ES"); - content.PublishCulture(CultureImpact.All, DateTime.Now, _propertyEditorCollection); + content.PublishCulture(CultureImpact.All, DateTime.UtcNow, _propertyEditorCollection); var i = 200; foreach (var property in content.Properties) @@ -430,7 +430,7 @@ public void Remember_Dirty_Properties() } content.Id = 10; - content.CreateDate = DateTime.Now; + content.CreateDate = DateTime.UtcNow; content.CreatorId = 22; content.Key = Guid.NewGuid(); content.Level = 3; @@ -438,7 +438,7 @@ public void Remember_Dirty_Properties() content.SortOrder = 5; content.TemplateId = 88; content.Trashed = true; - content.UpdateDate = DateTime.Now; + content.UpdateDate = DateTime.UtcNow; content.WriterId = 23; // Act @@ -497,7 +497,7 @@ public void Can_Serialize_Without_Error() } content.Id = 10; - content.CreateDate = DateTime.Now; + content.CreateDate = DateTime.UtcNow; content.CreatorId = 22; content.Key = Guid.NewGuid(); content.Level = 3; @@ -505,34 +505,13 @@ public void Can_Serialize_Without_Error() content.SortOrder = 5; content.TemplateId = 88; content.Trashed = false; - content.UpdateDate = DateTime.Now; + content.UpdateDate = DateTime.UtcNow; content.WriterId = 23; var json = JsonSerializer.Serialize(content); Debug.Print(json); } - /*[Test] - public void Cannot_Change_Property_With_Invalid_Value() - { - // Arrange - var contentType = ContentTypeBuilder.CreateTextpageContentType(); - var content = ContentBuilder.CreateTextpageContent(contentType); - - // Act - var model = new TestEditorModel - { - TestDateTime = DateTime.Now, - TestDouble = 1.2, - TestInt = 2, - TestReadOnly = "Read-only string", - TestString = "This is a test string" - }; - - // Assert - Assert.Throws(() => content.Properties["title"].Value = model); - }*/ - [Test] public void Can_Change_Property_Value_Through_Anonymous_Object() { diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberGroupTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberGroupTests.cs index 7efa4f5446d4..dabf14a5ab8f 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberGroupTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MemberGroupTests.cs @@ -60,7 +60,7 @@ private MemberGroup BuildMemberGroup() => .WithKey(Guid.NewGuid()) .WithName("Test Group") .WithCreatorId(4) - .WithCreateDate(DateTime.Now) - .WithUpdateDate(DateTime.Now) + .WithCreateDate(DateTime.UtcNow) + .WithUpdateDate(DateTime.UtcNow) .Build(); } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTests.cs index 2d9767c1ff9a..5b86317d842c 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/RelationTests.cs @@ -60,8 +60,8 @@ private Relation BuildRelation() => .BetweenIds(9, 8) .WithId(4) .WithComment("test comment") - .WithCreateDate(DateTime.Now) - .WithUpdateDate(DateTime.Now) + .WithCreateDate(DateTime.UtcNow) + .WithUpdateDate(DateTime.UtcNow) .WithKey(Guid.NewGuid()) .AddRelationType() .WithId(66) diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/TemplateTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/TemplateTests.cs index 5c4b1d0d9af2..062746f47ebb 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/TemplateTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/TemplateTests.cs @@ -68,8 +68,8 @@ private ITemplate BuildTemplate() => .WithId(3) .WithAlias("test") .WithName("Test") - .WithCreateDate(DateTime.Now) - .WithUpdateDate(DateTime.Now) + .WithCreateDate(DateTime.UtcNow) + .WithUpdateDate(DateTime.UtcNow) .WithKey(Guid.NewGuid()) .WithContent("blah") .AsMasterTemplate("master", 88) diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/VariationTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/VariationTests.cs index ec4204c5be9c..47ac40f6ef47 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/VariationTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/VariationTests.cs @@ -320,7 +320,7 @@ public void ContentPublishValues() // can publish value // and get edited and published values - Assert.IsTrue(content.PublishCulture(CultureImpact.All, DateTime.Now, _propertyEditorCollection)); + Assert.IsTrue(content.PublishCulture(CultureImpact.All, DateTime.UtcNow, _propertyEditorCollection)); Assert.AreEqual("a", content.GetValue("prop")); Assert.AreEqual("a", content.GetValue("prop", published: true)); @@ -350,9 +350,9 @@ public void ContentPublishValues() // can publish value // and get edited and published values - Assert.IsFalse(content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.Now, _propertyEditorCollection)); // no name + Assert.IsFalse(content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.UtcNow, _propertyEditorCollection)); // no name content.SetCultureName("name-fr", langFr); - Assert.IsTrue(content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.Now, _propertyEditorCollection)); + Assert.IsTrue(content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.UtcNow, _propertyEditorCollection)); Assert.IsNull(content.GetValue("prop")); Assert.IsNull(content.GetValue("prop", published: true)); Assert.AreEqual("c", content.GetValue("prop", langFr)); @@ -366,7 +366,7 @@ public void ContentPublishValues() Assert.IsNull(content.GetValue("prop", langFr, published: true)); // can publish all - Assert.IsTrue(content.PublishCulture(CultureImpact.All, DateTime.Now, _propertyEditorCollection)); + Assert.IsTrue(content.PublishCulture(CultureImpact.All, DateTime.UtcNow, _propertyEditorCollection)); Assert.IsNull(content.GetValue("prop")); Assert.IsNull(content.GetValue("prop", published: true)); Assert.AreEqual("c", content.GetValue("prop", langFr)); @@ -376,14 +376,14 @@ public void ContentPublishValues() content.UnpublishCulture(langFr); Assert.AreEqual("c", content.GetValue("prop", langFr)); Assert.IsNull(content.GetValue("prop", langFr, published: true)); - Assert.IsTrue(content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.Now, _propertyEditorCollection)); + Assert.IsTrue(content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.UtcNow, _propertyEditorCollection)); Assert.AreEqual("c", content.GetValue("prop", langFr)); Assert.AreEqual("c", content.GetValue("prop", langFr, published: true)); content.UnpublishCulture(); // clears invariant props if any Assert.IsNull(content.GetValue("prop")); Assert.IsNull(content.GetValue("prop", published: true)); - Assert.IsTrue(content.PublishCulture(CultureImpact.All, DateTime.Now, _propertyEditorCollection)); // publishes invariant props if any + Assert.IsTrue(content.PublishCulture(CultureImpact.All, DateTime.UtcNow, _propertyEditorCollection)); // publishes invariant props if any Assert.IsNull(content.GetValue("prop")); Assert.IsNull(content.GetValue("prop", published: true)); @@ -442,19 +442,19 @@ public void ContentPublishValuesWithMixedPropertyTypeVariations() var langFrImpact = CultureImpact.Explicit(langFr, true); Assert.IsTrue( - content.PublishCulture(langFrImpact, DateTime.Now, _propertyEditorCollection)); // succeeds because names are ok (not validating properties here) + content.PublishCulture(langFrImpact, DateTime.UtcNow, _propertyEditorCollection)); // succeeds because names are ok (not validating properties here) Assert.IsFalse( propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact)); // fails because prop1 is mandatory content.SetValue("prop1", "a", langFr); Assert.IsTrue( - content.PublishCulture(langFrImpact, DateTime.Now, _propertyEditorCollection)); // succeeds because names are ok (not validating properties here) + content.PublishCulture(langFrImpact, DateTime.UtcNow, _propertyEditorCollection)); // succeeds because names are ok (not validating properties here) // Fails because prop2 is mandatory and invariant and the item isn't published. // Invariant is validated against the default language except when there isn't a published version, in that case it's always validated. Assert.IsFalse(propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact)); content.SetValue("prop2", "x"); - Assert.IsTrue(content.PublishCulture(langFrImpact, DateTime.Now, _propertyEditorCollection)); // still ok... + Assert.IsTrue(content.PublishCulture(langFrImpact, DateTime.UtcNow, _propertyEditorCollection)); // still ok... Assert.IsTrue(propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact)); // now it's ok Assert.AreEqual("a", content.GetValue("prop1", langFr, published: true)); @@ -490,12 +490,12 @@ public void ContentPublishVariations() content.SetValue("prop", "a-es", langEs); // cannot publish without a name - Assert.IsFalse(content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.Now, _propertyEditorCollection)); + Assert.IsFalse(content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.UtcNow, _propertyEditorCollection)); // works with a name // and then FR is available, and published content.SetCultureName("name-fr", langFr); - Assert.IsTrue(content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.Now, _propertyEditorCollection)); + Assert.IsTrue(content.PublishCulture(CultureImpact.Explicit(langFr, false), DateTime.UtcNow, _propertyEditorCollection)); // now UK is available too content.SetCultureName("name-uk", langUk); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueEditorTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueEditorTests.cs index 93133ff66f27..3b15a08ce306 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueEditorTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/PropertyEditors/PropertyEditorValueEditorTests.cs @@ -129,7 +129,7 @@ public void Value_Editor_Can_Serialize_Decimal_Value_With_Empty_String() [Test] public void Value_Editor_Can_Serialize_Date_Value() { - var now = DateTime.Now; + var now = DateTime.UtcNow; var valueEditor = MockedValueEditors.CreateDataValueEditor(ValueTypes.Date); var prop = new Property(1, new PropertyType(Mock.Of(), "test", ValueStorageType.Date)); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Published/PropertyCacheVarianceTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Published/PropertyCacheVarianceTests.cs deleted file mode 100644 index 78357027efe4..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Published/PropertyCacheVarianceTests.cs +++ /dev/null @@ -1,382 +0,0 @@ -// using Moq; -// using NUnit.Framework; -// using Umbraco.Cms.Core.Cache; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Core.Models.PublishedContent; -// using Umbraco.Cms.Core.PropertyEditors; -// using Umbraco.Cms.Core.PublishedCache; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Infrastructure.PublishedCache.DataSource; -// using Property = Umbraco.Cms.Infrastructure.PublishedCache.Property; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Published; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class PropertyCacheVarianceTests -// { -// // This class tests various permutations of property value calculation across variance types and cache levels. -// // -// // Properties contain different "value levels", all of which are cached: -// // 1. The source value => the "raw" value from the client side editor (it can be different, but it's easiest to think of it like that). -// // 2. The intermediate value => a "temporary" value that is used to calculate the various "final" values. -// // 3. The object value => the "final" object value that is exposed in an IPublishedElement output. -// // 4. The XPath value => a legacy "final" value, don't think too hard on it. -// // 3. The delivery API object value => the "final" object value that is exposed in the Delivery API. -// // -// // Property values are cached based on a few rules: -// // 1. The property type variation and the parent content type variation determines how the intermediate value is cached. -// // The effective property variation is a product of both variations, meaning the property type and the content type -// // variations are combined in an OR. -// // The rules are as follows: -// // - ContentVariation.Nothing => the intermediate value is calculated once and reused across all variants (cultures and segments). -// // - ContentVariation.Culture => the intermediate value is calculated per culture and reused across all segments. -// // - ContentVariation.Segment => the intermediate value is calculated per segment and reused across all cultures. -// // - ContentVariation.CultureAndSegment => the intermediate value is calculated for all invoked culture and segment combinations. -// // 2. The property type cache level (which is usually derived from the property value converter). -// // - PropertyCacheLevel.Element => the final values are cached until the parent content item is updated. -// // - PropertyCacheLevel.Elements => the final values are cached until the _any_ content item is updated. -// // - PropertyCacheLevel.Snapshot => the final values are cached for the duration of the active cache snapshot (i.e. until the end of the current request). -// // - PropertyCacheLevel.None => the final values are never cached and will be re-calculated each time they're requested. -// -// // ### Invariant content type + invariant property type ### -// [TestCase( -// ContentVariation.Nothing, -// ContentVariation.Nothing, -// PropertyCacheLevel.Element, -// // no variation => the intermediate value is calculated only once -// // cache level => the final value is calculated only once -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)")] -// [TestCase( -// ContentVariation.Nothing, -// ContentVariation.Nothing, -// PropertyCacheLevel.Elements, -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)")] -// [TestCase( -// ContentVariation.Nothing, -// ContentVariation.Nothing, -// PropertyCacheLevel.Snapshot, -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)")] -// [TestCase( -// ContentVariation.Nothing, -// ContentVariation.Nothing, -// PropertyCacheLevel.None, -// // no variation => the intermediate value is calculated once -// // no cache => the final value is calculated for each request (reflects both changes in culture and segments) -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (da-DK:segment1)", -// "en-US:segment2 (da-DK:segment1)", -// "da-DK:segment2 (da-DK:segment1)")] -// // ### Culture variant content type + invariant property type ### -// [TestCase( -// ContentVariation.Culture, -// ContentVariation.Nothing, -// PropertyCacheLevel.Element, -// // culture variation => the intermediate value is calculated per culture (ignores segment changes until a culture changes) -// // cache level => the final value is calculated only once per culture (ignores segment changes until a culture changes) -// // NOTE: in this test, culture changes before segment, so the updated segment is never reflected here -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "da-DK:segment1 (da-DK:segment1)")] -// [TestCase( -// ContentVariation.Culture, -// ContentVariation.Nothing, -// PropertyCacheLevel.Elements, -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "da-DK:segment1 (da-DK:segment1)")] -// [TestCase( -// ContentVariation.Culture, -// ContentVariation.Nothing, -// PropertyCacheLevel.Snapshot, -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "da-DK:segment1 (da-DK:segment1)")] -// [TestCase( -// ContentVariation.Culture, -// ContentVariation.Nothing, -// PropertyCacheLevel.None, -// // culture variation => the intermediate value is calculated per culture (ignores segment changes until a culture changes) -// // no cache => the final value is calculated for each request (reflects both changes in culture and segments) -// // NOTE: in this test, culture changes before segment, so the updated segment is never reflected in the intermediate value here -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment2 (en-US:segment1)", -// "da-DK:segment2 (da-DK:segment1)")] -// // NOTE: As the tests above show, cache levels Element, Elements and Snapshot all yield the same values in this -// // test, because we are efficiently executing the test in a snapshot. From here on out we're only building -// // test cases for Element and None. -// // ### Segment variant content type + invariant property type ### -// [TestCase( -// ContentVariation.Segment, -// ContentVariation.Nothing, -// PropertyCacheLevel.Element, -// // segment variation => the intermediate value is calculated per segment (ignores culture changes until a segment changes) -// // cache level => the final value is calculated only once per segment (ignores culture changes until a segment changes) -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "en-US:segment2 (en-US:segment2)")] -// [TestCase( -// ContentVariation.Segment, -// ContentVariation.Nothing, -// PropertyCacheLevel.None, -// // segment variation => the intermediate value is calculated per segment (ignores culture changes until a segment changes) -// // no cache => the final value is calculated for each request (reflects both changes in culture and segments) -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (da-DK:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "da-DK:segment2 (en-US:segment2)")] -// // ### Culture and segment variant content type + invariant property type ### -// [TestCase( -// ContentVariation.CultureAndSegment, -// ContentVariation.Nothing, -// PropertyCacheLevel.Element, -// // culture and segment variation => the intermediate value is calculated per culture and segment -// // cache level => the final value is calculated only once per culture and segment (efficiently on every request in this test) -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "da-DK:segment2 (da-DK:segment2)")] -// [TestCase( -// ContentVariation.CultureAndSegment, -// ContentVariation.Nothing, -// PropertyCacheLevel.None, -// // culture and segment variation => the intermediate value is calculated per culture and segment -// // no cache => the final value is calculated for each request -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "da-DK:segment2 (da-DK:segment2)")] -// // ### Invariant content type + culture variant property type ### -// [TestCase( -// ContentVariation.Nothing, -// ContentVariation.Culture, -// PropertyCacheLevel.Element, -// // same behaviour as culture variation on content type + no variation on property type, see comments above -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "da-DK:segment1 (da-DK:segment1)")] -// [TestCase( -// ContentVariation.Nothing, -// ContentVariation.Culture, -// PropertyCacheLevel.None, -// // same behaviour as culture variation on content type + no variation on property type, see comments above -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment2 (en-US:segment1)", -// "da-DK:segment2 (da-DK:segment1)")] -// // ### Invariant content type + segment variant property type ### -// [TestCase( -// ContentVariation.Nothing, -// ContentVariation.Segment, -// PropertyCacheLevel.Element, -// // same behaviour as segment variation on content type + no variation on property type, see comments above -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "en-US:segment2 (en-US:segment2)")] -// [TestCase( -// ContentVariation.Nothing, -// ContentVariation.Segment, -// PropertyCacheLevel.None, -// // same behaviour as segment variation on content type + no variation on property type, see comments above -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (da-DK:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "da-DK:segment2 (en-US:segment2)")] -// // ### Invariant content type + culture and segment variant property type ### -// [TestCase( -// ContentVariation.Nothing, -// ContentVariation.CultureAndSegment, -// PropertyCacheLevel.Element, -// // same behaviour as culture and segment variation on content type + no variation on property type, see comments above -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "da-DK:segment2 (da-DK:segment2)")] -// [TestCase( -// ContentVariation.Nothing, -// ContentVariation.CultureAndSegment, -// PropertyCacheLevel.None, -// // same behaviour as culture and segment variation on content type + no variation on property type, see comments above -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "da-DK:segment2 (da-DK:segment2)")] -// // ### Culture variant content type + segment variant property type ### -// [TestCase( -// ContentVariation.Culture, -// ContentVariation.Segment, -// PropertyCacheLevel.Element, -// // same behaviour as culture and segment variation on content type + no variation on property type, see comments above -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "da-DK:segment2 (da-DK:segment2)")] -// [TestCase( -// ContentVariation.Culture, -// ContentVariation.Segment, -// PropertyCacheLevel.None, -// // same behaviour as culture and segment variation on content type + no variation on property type, see comments above -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "da-DK:segment2 (da-DK:segment2)")] -// public void ContentType_PropertyType_Variation_Cache_Values( -// ContentVariation contentTypeVariation, -// ContentVariation propertyTypeVariation, -// PropertyCacheLevel propertyCacheLevel, -// string expectedValue1DaDkSegment1, -// string expectedValue2EnUsSegment1, -// string expectedValue3EnUsSegment2, -// string expectedValue4DaDkSegment2) -// { -// var variationContextCulture = "da-DK"; -// var variationContextSegment = "segment1"; -// var property = CreateProperty( -// contentTypeVariation, -// propertyTypeVariation, -// propertyCacheLevel, -// () => variationContextCulture, -// () => variationContextSegment); -// -// Assert.AreEqual(expectedValue1DaDkSegment1, property.GetValue()); -// -// variationContextCulture = "en-US"; -// Assert.AreEqual(expectedValue2EnUsSegment1, property.GetValue()); -// -// variationContextSegment = "segment2"; -// Assert.AreEqual(expectedValue3EnUsSegment2, property.GetValue()); -// -// variationContextCulture = "da-DK"; -// Assert.AreEqual(expectedValue4DaDkSegment2, property.GetValue()); -// } -// -// [TestCase( -// ContentVariation.Culture, -// ContentVariation.Nothing, -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "da-DK:segment1 (da-DK:segment1)")] -// [TestCase( -// ContentVariation.Segment, -// ContentVariation.Nothing, -// "da-DK:segment1 (da-DK:segment1)", -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "en-US:segment2 (en-US:segment2)")] -// [TestCase( -// ContentVariation.Culture, -// ContentVariation.Segment, -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "da-DK:segment2 (da-DK:segment2)")] -// [TestCase( -// ContentVariation.CultureAndSegment, -// ContentVariation.Nothing, -// "da-DK:segment1 (da-DK:segment1)", -// "en-US:segment1 (en-US:segment1)", -// "en-US:segment2 (en-US:segment2)", -// "da-DK:segment2 (da-DK:segment2)")] -// public void ContentType_PropertyType_Variation_Are_Interchangeable( -// ContentVariation variation1, -// ContentVariation variation2, -// string expectedValue1DaDkSegment1, -// string expectedValue2EnUsSegment1, -// string expectedValue3EnUsSegment2, -// string expectedValue4DaDkSegment2) -// { -// var scenarios = new[] -// { -// new { ContentTypeVariation = variation1, PropertyTypeVariation = variation2 }, -// new { ContentTypeVariation = variation2, PropertyTypeVariation = variation1 } -// }; -// -// foreach (var scenario in scenarios) -// { -// var variationContextCulture = "da-DK"; -// var variationContextSegment = "segment1"; -// var property = CreateProperty( -// scenario.ContentTypeVariation, -// scenario.PropertyTypeVariation, -// PropertyCacheLevel.Element, -// () => variationContextCulture, -// () => variationContextSegment); -// -// Assert.AreEqual(expectedValue1DaDkSegment1, property.GetValue()); -// -// variationContextCulture = "en-US"; -// Assert.AreEqual(expectedValue2EnUsSegment1, property.GetValue()); -// -// variationContextSegment = "segment2"; -// Assert.AreEqual(expectedValue3EnUsSegment2, property.GetValue()); -// -// variationContextCulture = "da-DK"; -// Assert.AreEqual(expectedValue4DaDkSegment2, property.GetValue()); -// } -// } -// -// /// -// /// Creates a new property with a mocked publishedSnapshotAccessor that uses a VariationContext that reads culture and segment information from the passed in functions. -// /// -// private Property CreateProperty(ContentVariation contentTypeVariation, ContentVariation propertyTypeVariation, PropertyCacheLevel propertyTypeCacheLevel, Func getCulture, Func getSegment) -// { -// var contentType = new Mock(); -// contentType.SetupGet(c => c.PropertyTypes).Returns(Array.Empty()); -// contentType.SetupGet(c => c.Variations).Returns(contentTypeVariation); -// -// var contentNode = new ContentNode(123, Guid.NewGuid(), contentType.Object, 1, string.Empty, 1, 1, DateTime.Now, 1); -// var contentData = new ContentData("bla", "bla", 1, DateTime.Now, 1, 1, true, new Dictionary(), null); -// -// var elementCache = new FastDictionaryAppCache(); -// var snapshotCache = new FastDictionaryAppCache(); -// var publishedSnapshotMock = new Mock(); -// publishedSnapshotMock.SetupGet(p => p.ElementsCache).Returns(elementCache); -// publishedSnapshotMock.SetupGet(p => p.SnapshotCache).Returns(snapshotCache); -// -// var publishedSnapshot = publishedSnapshotMock.Object; -// var publishedSnapshotAccessor = new Mock(); -// publishedSnapshotAccessor.Setup(p => p.TryGetPublishedSnapshot(out publishedSnapshot)).Returns(true); -// -// var variationContextAccessorMock = new Mock(); -// variationContextAccessorMock -// .SetupGet(mock => mock.VariationContext) -// .Returns(() => new VariationContext(getCulture(), getSegment())); -// -// var content = new PublishedContent( -// contentNode, -// contentData, -// publishedSnapshotAccessor.Object, -// variationContextAccessorMock.Object, -// Mock.Of()); -// -// var propertyType = new Mock(); -// propertyType.SetupGet(p => p.CacheLevel).Returns(propertyTypeCacheLevel); -// propertyType.SetupGet(p => p.DeliveryApiCacheLevel).Returns(propertyTypeCacheLevel); -// propertyType.SetupGet(p => p.Variations).Returns(propertyTypeVariation); -// propertyType -// .Setup(p => p.ConvertSourceToInter(It.IsAny(), It.IsAny(), It.IsAny())) -// .Returns(() => $"{getCulture()}:{getSegment()}"); -// propertyType -// .Setup(p => p.ConvertInterToObject(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) -// .Returns((IPublishedElement _, PropertyCacheLevel _, object? inter, bool _) => $"{getCulture()}:{getSegment()} ({inter})" ); -// -// return new Property(propertyType.Object, content, publishedSnapshotAccessor.Object); -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Published/PublishedContentVarianceTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Published/PublishedContentVarianceTests.cs deleted file mode 100644 index e603d682c117..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Published/PublishedContentVarianceTests.cs +++ /dev/null @@ -1,175 +0,0 @@ -// using Moq; -// using NUnit.Framework; -// using Umbraco.Cms.Core.Cache; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Core.Models.PublishedContent; -// using Umbraco.Cms.Core.PropertyEditors; -// using Umbraco.Cms.Core.PublishedCache; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Infrastructure.PublishedCache.DataSource; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Published; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class PublishedContentVarianceTests -// { -// private const string PropertyTypeAlias = "theProperty"; -// private const string DaCulture = "da-DK"; -// private const string EnCulture = "en-US"; -// private const string Segment1 = "segment1"; -// private const string Segment2 = "segment2"; -// -// [Test] -// public void No_Content_Variation_Can_Get_Invariant_Property() -// { -// var content = CreatePublishedContent(ContentVariation.Nothing, ContentVariation.Nothing); -// var value = GetPropertyValue(content); -// Assert.AreEqual("Invariant property value", value); -// } -// -// [TestCase(DaCulture)] -// [TestCase(EnCulture)] -// [TestCase("")] -// public void Content_Culture_Variation_Can_Get_Invariant_Property(string culture) -// { -// var content = CreatePublishedContent(ContentVariation.Culture, ContentVariation.Nothing, variationContextCulture: culture); -// var value = GetPropertyValue(content); -// Assert.AreEqual("Invariant property value", value); -// } -// -// [TestCase(Segment1)] -// [TestCase(Segment2)] -// [TestCase("")] -// public void Content_Segment_Variation_Can_Get_Invariant_Property(string segment) -// { -// var content = CreatePublishedContent(ContentVariation.Culture, ContentVariation.Nothing, variationContextSegment: segment); -// var value = GetPropertyValue(content); -// Assert.AreEqual("Invariant property value", value); -// } -// -// [TestCase(DaCulture, "DaDk property value")] -// [TestCase(EnCulture, "EnUs property value")] -// public void Content_Culture_Variation_Can_Get_Culture_Variant_Property(string culture, string expectedValue) -// { -// var content = CreatePublishedContent(ContentVariation.Culture, ContentVariation.Culture, variationContextCulture: culture); -// var value = GetPropertyValue(content); -// Assert.AreEqual(expectedValue, value); -// } -// -// [TestCase(Segment1, "Segment1 property value")] -// [TestCase(Segment2, "Segment2 property value")] -// public void Content_Segment_Variation_Can_Get_Segment_Variant_Property(string segment, string expectedValue) -// { -// var content = CreatePublishedContent(ContentVariation.Segment, ContentVariation.Segment, variationContextSegment: segment); -// var value = GetPropertyValue(content); -// Assert.AreEqual(expectedValue, value); -// } -// -// [TestCase(DaCulture, Segment1, "DaDk Segment1 property value")] -// [TestCase(DaCulture, Segment2, "DaDk Segment2 property value")] -// [TestCase(EnCulture, Segment1, "EnUs Segment1 property value")] -// [TestCase(EnCulture, Segment2, "EnUs Segment2 property value")] -// public void Content_Culture_And_Segment_Variation_Can_Get_Culture_And_Segment_Variant_Property(string culture, string segment, string expectedValue) -// { -// var content = CreatePublishedContent(ContentVariation.CultureAndSegment, ContentVariation.CultureAndSegment, variationContextCulture: culture, variationContextSegment: segment); -// var value = GetPropertyValue(content); -// Assert.AreEqual(expectedValue, value); -// } -// -// [TestCase(DaCulture, Segment1, "DaDk property value")] -// [TestCase(DaCulture, Segment2, "DaDk property value")] -// [TestCase(EnCulture, Segment1, "EnUs property value")] -// [TestCase(EnCulture, Segment2, "EnUs property value")] -// public void Content_Culture_And_Segment_Variation_Can_Get_Culture_Variant_Property(string culture, string segment, string expectedValue) -// { -// var content = CreatePublishedContent(ContentVariation.CultureAndSegment, ContentVariation.Culture, variationContextCulture: culture, variationContextSegment: segment); -// var value = GetPropertyValue(content); -// Assert.AreEqual(expectedValue, value); -// } -// -// [TestCase(DaCulture, Segment1, "Segment1 property value")] -// [TestCase(DaCulture, Segment2, "Segment2 property value")] -// [TestCase(EnCulture, Segment1, "Segment1 property value")] -// [TestCase(EnCulture, Segment2, "Segment2 property value")] -// public void Content_Culture_And_Segment_Variation_Can_Get_Segment_Variant_Property(string culture, string segment, string expectedValue) -// { -// var content = CreatePublishedContent(ContentVariation.CultureAndSegment, ContentVariation.Segment, variationContextCulture: culture, variationContextSegment: segment); -// var value = GetPropertyValue(content); -// Assert.AreEqual(expectedValue, value); -// } -// -// private object? GetPropertyValue(IPublishedContent content) => content.GetProperty(PropertyTypeAlias)!.GetValue(); -// -// private IPublishedContent CreatePublishedContent(ContentVariation contentTypeVariation, ContentVariation propertyTypeVariation, string? variationContextCulture = null, string? variationContextSegment = null) -// { -// var propertyType = new Mock(); -// propertyType.SetupGet(p => p.Alias).Returns(PropertyTypeAlias); -// propertyType.SetupGet(p => p.CacheLevel).Returns(PropertyCacheLevel.None); -// propertyType.SetupGet(p => p.DeliveryApiCacheLevel).Returns(PropertyCacheLevel.None); -// propertyType.SetupGet(p => p.Variations).Returns(propertyTypeVariation); -// propertyType -// .Setup(p => p.ConvertSourceToInter(It.IsAny(), It.IsAny(), It.IsAny())) -// .Returns((IPublishedElement _, object? source, bool _) => source); -// propertyType -// .Setup(p => p.ConvertInterToObject(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) -// .Returns((IPublishedElement _, PropertyCacheLevel _, object? inter, bool _) => inter); -// -// var contentType = new Mock(); -// contentType.SetupGet(c => c.PropertyTypes).Returns(new[] { propertyType.Object }); -// contentType.SetupGet(c => c.Variations).Returns(contentTypeVariation); -// -// var propertyData = new List(); -// -// switch (propertyTypeVariation) -// { -// case ContentVariation.Culture: -// propertyData.Add(CreatePropertyData("EnUs property value", culture: EnCulture)); -// propertyData.Add(CreatePropertyData("DaDk property value", culture: DaCulture)); -// break; -// case ContentVariation.Segment: -// propertyData.Add(CreatePropertyData("Segment1 property value", segment: Segment1)); -// propertyData.Add(CreatePropertyData("Segment2 property value", segment: Segment2)); -// break; -// case ContentVariation.CultureAndSegment: -// propertyData.Add(CreatePropertyData("EnUs Segment1 property value", culture: EnCulture, segment: Segment1)); -// propertyData.Add(CreatePropertyData("EnUs Segment2 property value", culture: EnCulture, segment: Segment2)); -// propertyData.Add(CreatePropertyData("DaDk Segment1 property value", culture: DaCulture, segment: Segment1)); -// propertyData.Add(CreatePropertyData("DaDk Segment2 property value", culture: DaCulture, segment: Segment2)); -// break; -// case ContentVariation.Nothing: -// propertyData.Add(CreatePropertyData("Invariant property value")); -// break; -// } -// -// var properties = new Dictionary { { PropertyTypeAlias, propertyData.ToArray() } }; -// -// var contentNode = new ContentNode(123, Guid.NewGuid(), contentType.Object, 1, string.Empty, 1, 1, DateTime.Now, 1); -// var contentData = new ContentData("bla", "bla", 1, DateTime.Now, 1, 1, true, properties, null); -// -// var elementCache = new FastDictionaryAppCache(); -// var snapshotCache = new FastDictionaryAppCache(); -// var publishedSnapshotMock = new Mock(); -// publishedSnapshotMock.SetupGet(p => p.ElementsCache).Returns(elementCache); -// publishedSnapshotMock.SetupGet(p => p.SnapshotCache).Returns(snapshotCache); -// -// var publishedSnapshot = publishedSnapshotMock.Object; -// var publishedSnapshotAccessor = new Mock(); -// publishedSnapshotAccessor.Setup(p => p.TryGetPublishedSnapshot(out publishedSnapshot)).Returns(true); -// -// var variationContextAccessorMock = new Mock(); -// variationContextAccessorMock -// .SetupGet(mock => mock.VariationContext) -// .Returns(() => new VariationContext(variationContextCulture, variationContextSegment)); -// -// return new PublishedContent( -// contentNode, -// contentData, -// publishedSnapshotAccessor.Object, -// variationContextAccessorMock.Object, -// Mock.Of()); -// -// PropertyData CreatePropertyData(string value, string? culture = null, string? segment = null) -// => new() { Culture = culture ?? string.Empty, Segment = segment ?? string.Empty, Value = value }; -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/PublishedRouterTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/PublishedRouterTests.cs index 44f660a9c65e..812b9f996a4d 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/PublishedRouterTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/PublishedRouterTests.cs @@ -83,8 +83,8 @@ private Mock GetPublishedContentMock() var pc = new Mock(); pc.Setup(content => content.Id).Returns(1); pc.Setup(content => content.Name).Returns("test"); - pc.Setup(content => content.CreateDate).Returns(DateTime.Now); - pc.Setup(content => content.UpdateDate).Returns(DateTime.Now); + pc.Setup(content => content.CreateDate).Returns(DateTime.UtcNow); + pc.Setup(content => content.UpdateDate).Returns(DateTime.UtcNow); pc.Setup(content => content.Path).Returns("-1,1"); pc.Setup(content => content.Properties).Returns(new Collection()); pc.Setup(content => content.ContentType) diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UrlProviderWithoutHideTopLevelNodeFromPathTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UrlProviderWithoutHideTopLevelNodeFromPathTests.cs deleted file mode 100644 index 5e952814346d..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UrlProviderWithoutHideTopLevelNodeFromPathTests.cs +++ /dev/null @@ -1,311 +0,0 @@ -// using System.Collections.Generic; -// using System.Linq; -// using Moq; -// using NUnit.Framework; -// using Umbraco.Cms.Core.Cache; -// using Umbraco.Cms.Core.Configuration.Models; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Core.Models.PublishedContent; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Infrastructure.PublishedCache.DataSource; -// using Umbraco.Cms.Tests.Common.Builders; -// using Umbraco.Cms.Tests.Common.Builders.Extensions; -// using Umbraco.Cms.Tests.Common.Published; -// using Umbraco.Cms.Tests.UnitTests.TestHelpers; -// using Umbraco.Extensions; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Routing; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class UrlProviderWithoutHideTopLevelNodeFromPathTests : PublishedSnapshotServiceTestBase -// { -// [SetUp] -// public override void Setup() -// { -// base.Setup(); -// -// GlobalSettings.HideTopLevelNodeFromPath = false; -// } -// -// private const string CacheKeyPrefix = "NuCache.ContentCache.RouteByContent"; -// -// private void PopulateCache(string culture = "fr-FR") -// { -// var dataTypes = GetDefaultDataTypes(); -// var propertyDataTypes = new Dictionary -// { -// // we only have one data type for this test which will be resolved with string empty. -// [string.Empty] = dataTypes[0], -// }; -// var contentType1 = new ContentType(ShortStringHelper, -1); -// -// var rootData = new ContentDataBuilder() -// .WithName("Page" + Guid.NewGuid()) -// .WithCultureInfos(new Dictionary -// { -// [culture] = new() { Name = "root", IsDraft = true, Date = DateTime.Now, UrlSegment = "root" }, -// }) -// .Build(ShortStringHelper, propertyDataTypes, contentType1, "alias"); -// -// var root = ContentNodeKitBuilder.CreateWithContent( -// contentType1.Id, -// 9876, -// "-1,9876", -// draftData: rootData, -// publishedData: rootData); -// -// var parentData = new ContentDataBuilder() -// .WithName("Page" + Guid.NewGuid()) -// .WithCultureInfos(new Dictionary -// { -// [culture] = new() { Name = "home", IsDraft = true, Date = DateTime.Now, UrlSegment = "home" }, -// }) -// .Build(); -// -// var parent = ContentNodeKitBuilder.CreateWithContent( -// contentType1.Id, -// 5432, -// "-1,9876,5432", -// parentContentId: 9876, -// draftData: parentData, -// publishedData: parentData); -// -// var contentData = new ContentDataBuilder() -// .WithName("Page" + Guid.NewGuid()) -// .WithCultureInfos(new Dictionary -// { -// [culture] = new() { Name = "name-fr2", IsDraft = true, Date = DateTime.Now, UrlSegment = "test-fr" }, -// }) -// .Build(); -// -// var content = ContentNodeKitBuilder.CreateWithContent( -// contentType1.Id, -// 1234, -// "-1,9876,5432,1234", -// parentContentId: 5432, -// draftData: contentData, -// publishedData: contentData); -// -// InitializedCache(new[] { root, parent, content }, new[] { contentType1 }, dataTypes); -// } -// -// private void SetDomains1() -// { -// var domainService = Mock.Get(DomainService); -// -// domainService.Setup(service => service.GetAll(It.IsAny())) -// .Returns((bool incWildcards) => new[] -// { -// new UmbracoDomain("http://example.us/") { Id = 1, RootContentId = 9876, LanguageIsoCode = "en-US" }, -// new UmbracoDomain("http://example.fr/") { Id = 2, RootContentId = 9876, LanguageIsoCode = "fr-FR" }, -// }); -// } -// -// /// -// /// This checks that when we retrieve a NiceUrl for multiple items that there are no issues with cache overlap -// /// and that they are all cached correctly. -// /// -// [Test] -// public void Ensure_Cache_Is_Correct() -// { -// var requestHandlerSettings = new RequestHandlerSettings { AddTrailingSlash = false }; -// -// var xml = PublishedContentXml.BaseWebTestXml(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// var umbracoContextAccessor = GetUmbracoContextAccessor("/test"); -// var umbracoContext = umbracoContextAccessor.GetRequiredUmbracoContext(); -// var urlProvider = GetUrlProvider(umbracoContextAccessor, requestHandlerSettings, new WebRoutingSettings(), out _); -// -// var samples = new Dictionary -// { -// { 1046, "/home" }, -// { 1173, "/home/sub1" }, -// { 1174, "/home/sub1/sub2" }, -// { 1176, "/home/sub1/sub-3" }, -// { 1177, "/home/sub1/custom-sub-1" }, -// { 1178, "/home/sub1/custom-sub-2" }, -// { 1175, "/home/sub-2" }, -// { 1172, "/test-page" }, -// }; -// -// foreach (var sample in samples) -// { -// var result = urlProvider.GetUrl(sample.Key); -// Assert.AreEqual(sample.Value, result); -// } -// -// var randomSample = new KeyValuePair(1177, "/home/sub1/custom-sub-1"); -// for (var i = 0; i < 5; i++) -// { -// var result = urlProvider.GetUrl(randomSample.Key); -// Assert.AreEqual(randomSample.Value, result); -// } -// -// var cache = (FastDictionaryAppCache)umbracoContext.PublishedSnapshot.ElementsCache; -// var cachedRoutes = cache.Keys.Where(x => x.StartsWith(CacheKeyPrefix)).ToList(); -// Assert.AreEqual(8, cachedRoutes.Count); -// -// foreach (var sample in samples) -// { -// var cacheKey = $"{CacheKeyPrefix}[P:{sample.Key}]"; -// var found = (string)cache.Get(cacheKey); -// Assert.IsNotNull(found); -// Assert.AreEqual(sample.Value, found); -// } -// } -// -// [TestCase(1046, "/home/")] -// [TestCase(1173, "/home/sub1/")] -// [TestCase(1174, "/home/sub1/sub2/")] -// [TestCase(1176, "/home/sub1/sub-3/")] -// [TestCase(1177, "/home/sub1/custom-sub-1/")] -// [TestCase(1178, "/home/sub1/custom-sub-2/")] -// [TestCase(1175, "/home/sub-2/")] -// [TestCase(1172, "/test-page/")] -// public void Get_Url_Not_Hiding_Top_Level(int nodeId, string niceUrlMatch) -// { -// var requestHandlerSettings = new RequestHandlerSettings { AddTrailingSlash = true }; -// -// var xml = PublishedContentXml.BaseWebTestXml(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// var umbracoContextAccessor = GetUmbracoContextAccessor("/test"); -// var urlProvider = GetUrlProvider(umbracoContextAccessor, requestHandlerSettings, new WebRoutingSettings(), out _); -// -// var result = urlProvider.GetUrl(nodeId); -// Assert.AreEqual(niceUrlMatch, result); -// } -// -// [Test] -// [TestCase("fr-FR", ExpectedResult = "#")] // Non default cultures cannot return urls -// [TestCase("en-US", ExpectedResult = "/root/home/test-fr/")] // Default culture can return urls -// public string Get_Url_For_Culture_Variant_Without_Domains_Non_Current_Url(string culture) -// { -// const string currentUri = "http://example.us/test"; -// -// var requestHandlerSettings = new RequestHandlerSettings { AddTrailingSlash = true }; -// -// PopulateCache(culture); -// -// var umbracoContextAccessor = GetUmbracoContextAccessor(currentUri); -// var urlProvider = GetUrlProvider(umbracoContextAccessor, requestHandlerSettings, new WebRoutingSettings(), out _); -// -// // even though we are asking for a specific culture URL, there are no domains assigned so all that can be returned is a normal relative URL. -// var url = urlProvider.GetUrl(1234, culture: culture); -// -// return url; -// } -// -// /// -// /// This tests DefaultUrlProvider.GetUrl with a specific culture when the current URL is the culture specific domain -// /// -// [Test] -// public void Get_Url_For_Culture_Variant_With_Current_Url() -// { -// const string currentUri = "http://example.fr/test"; -// -// var requestHandlerSettings = new RequestHandlerSettings { AddTrailingSlash = true }; -// -// PopulateCache(); -// -// SetDomains1(); -// -// var umbracoContextAccessor = GetUmbracoContextAccessor(currentUri); -// var urlProvider = GetUrlProvider(umbracoContextAccessor, requestHandlerSettings, new WebRoutingSettings(), out _); -// -// var url = urlProvider.GetUrl(1234, culture: "fr-FR"); -// -// Assert.AreEqual("/home/test-fr/", url); -// } -// -// /// -// /// This tests DefaultUrlProvider.GetUrl with a specific culture when the current URL is not the culture specific -// /// domain -// /// -// [Test] -// public void Get_Url_For_Culture_Variant_Non_Current_Url() -// { -// const string currentUri = "http://example.us/test"; -// -// var requestHandlerSettings = new RequestHandlerSettings { AddTrailingSlash = true }; -// -// PopulateCache(); -// -// SetDomains1(); -// -// var umbracoContextAccessor = GetUmbracoContextAccessor(currentUri); -// var urlProvider = GetUrlProvider(umbracoContextAccessor, requestHandlerSettings, new WebRoutingSettings(), out _); -// var url = urlProvider.GetUrl(1234, culture: "fr-FR"); -// -// // the current uri is not the culture specific domain we want, so the result is an absolute path to the culture specific domain -// Assert.AreEqual("http://example.fr/home/test-fr/", url); -// } -// -// [Test] -// public void Get_Url_Relative_Or_Absolute() -// { -// var requestHandlerSettings = new RequestHandlerSettings { AddTrailingSlash = true }; -// -// var xml = PublishedContentXml.BaseWebTestXml(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// var umbracoContextAccessor = GetUmbracoContextAccessor("http://example.com/test"); -// -// var urlProvider = GetUrlProvider(umbracoContextAccessor, requestHandlerSettings, new WebRoutingSettings(), out _); -// -// Assert.AreEqual("/home/sub1/custom-sub-1/", urlProvider.GetUrl(1177)); -// -// urlProvider.Mode = UrlMode.Absolute; -// Assert.AreEqual("http://example.com/home/sub1/custom-sub-1/", urlProvider.GetUrl(1177)); -// } -// -// [Test] -// public void Get_Url_Unpublished() -// { -// var requestHandlerSettings = new RequestHandlerSettings(); -// -// var xml = PublishedContentXml.BaseWebTestXml(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// var umbracoContextAccessor = GetUmbracoContextAccessor("http://example.com/test"); -// -// var urlProvider = GetUrlProvider(umbracoContextAccessor, requestHandlerSettings, new WebRoutingSettings(), out _); -// -// // mock the Umbraco settings that we need -// Assert.AreEqual("#", urlProvider.GetUrl(999999)); -// -// urlProvider.Mode = UrlMode.Absolute; -// -// Assert.AreEqual("#", urlProvider.GetUrl(999999)); -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Services/AuditEntryServiceTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Services/AuditEntryServiceTests.cs index 523cd174f112..745ba30ad569 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Services/AuditEntryServiceTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Services/AuditEntryServiceTests.cs @@ -49,7 +49,7 @@ public async Task WriteAsync_Calls_Repository_With_Correct_Values() Assert.AreEqual(Constants.Security.SuperUserKey, item.PerformingUserKey); Assert.AreEqual("performingDetails", item.PerformingDetails); Assert.AreEqual("performingIp", item.PerformingIp); - Assert.AreEqual(date, item.EventDateUtc); + Assert.AreEqual(date, item.EventDate); Assert.AreEqual(Constants.Security.UnknownUserId, item.AffectedUserId); Assert.AreEqual(null, item.AffectedUserKey); Assert.AreEqual("affectedDetails", item.AffectedDetails); @@ -77,7 +77,7 @@ public async Task WriteAsync_Calls_Repository_With_Correct_Values() Assert.AreEqual(Constants.Security.SuperUserId, result.PerformingUserId); Assert.AreEqual("performingDetails", result.PerformingDetails); Assert.AreEqual("performingIp", result.PerformingIp); - Assert.AreEqual(date, result.EventDateUtc); + Assert.AreEqual(date, result.EventDate); Assert.AreEqual(Constants.Security.UnknownUserId, result.AffectedUserId); Assert.AreEqual("affectedDetails", result.AffectedDetails); Assert.AreEqual("umbraco/test", result.EventType); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/ContentSerializationTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/ContentSerializationTests.cs deleted file mode 100644 index 8f885772db2d..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/ContentSerializationTests.cs +++ /dev/null @@ -1,105 +0,0 @@ -// using Moq; -// using NUnit.Framework; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Core.PropertyEditors; -// using Umbraco.Cms.Infrastructure.PublishedCache.DataSource; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class ContentSerializationTests -// { -// [Test] -// public void GivenACacheModel_WhenItsSerializedAndDeserializedWithAnySerializer_TheResultsAreTheSame() -// { -// var jsonSerializer = new JsonContentNestedDataSerializer(); -// var msgPackSerializer = new MsgPackContentNestedDataSerializer(Mock.Of()); -// -// var now = DateTime.Now; -// var cacheModel = new ContentCacheDataModel -// { -// PropertyData = new Dictionary -// { -// ["propertyOne"] = -// new[] { new PropertyData { Culture = "en-US", Segment = "test", Value = "hello world" } }, -// ["propertyTwo"] = new[] -// { -// new PropertyData { Culture = "en-US", Segment = "test", Value = "Lorem ipsum" }, -// }, -// }, -// CultureData = new Dictionary -// { -// ["en-US"] = new() { Date = now, IsDraft = false, Name = "Home", UrlSegment = "home" }, -// }, -// UrlSegment = "home", -// }; -// -// var content = Mock.Of(x => x.ContentTypeId == 1); -// -// var json = jsonSerializer.Serialize(content, cacheModel, false).StringData; -// var msgPack = msgPackSerializer.Serialize(content, cacheModel, false).ByteData; -// -// Console.WriteLine(json); -// Console.WriteLine(msgPackSerializer.ToJson(msgPack)); -// -// var jsonContent = jsonSerializer.Deserialize(content, json, null, false); -// var msgPackContent = msgPackSerializer.Deserialize(content, null, msgPack, false); -// -// CollectionAssert.AreEqual(jsonContent.CultureData.Keys, msgPackContent.CultureData.Keys); -// CollectionAssert.AreEqual(jsonContent.PropertyData.Keys, msgPackContent.PropertyData.Keys); -// CollectionAssert.AreEqual(jsonContent.CultureData.Values, msgPackContent.CultureData.Values, new CultureVariationComparer()); -// CollectionAssert.AreEqual(jsonContent.PropertyData.Values, msgPackContent.PropertyData.Values, new PropertyDataComparer()); -// Assert.AreEqual(jsonContent.UrlSegment, msgPackContent.UrlSegment); -// } -// -// public class CultureVariationComparer : Comparer -// { -// public override int Compare(CultureVariation x, CultureVariation y) -// { -// if (x == null && y == null) -// { -// return 0; -// } -// -// if (x == null && y != null) -// { -// return -1; -// } -// -// if (x != null && y == null) -// { -// return 1; -// } -// -// return x.Date.CompareTo(y.Date) | x.IsDraft.CompareTo(y.IsDraft) | x.Name.CompareTo(y.Name) | -// x.UrlSegment.CompareTo(y.UrlSegment); -// } -// } -// -// public class PropertyDataComparer : Comparer -// { -// public override int Compare(PropertyData x, PropertyData y) -// { -// if (x == null && y == null) -// { -// return 0; -// } -// -// if (x == null && y != null) -// { -// return -1; -// } -// -// if (x != null && y == null) -// { -// return 1; -// } -// -// var xVal = x.Value?.ToString() ?? string.Empty; -// var yVal = y.Value?.ToString() ?? string.Empty; -// -// return x.Culture.CompareTo(y.Culture) | x.Segment.CompareTo(y.Segment) | xVal.CompareTo(yVal); -// } -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishContentCacheTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishContentCacheTests.cs deleted file mode 100644 index e50550b033ac..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishContentCacheTests.cs +++ /dev/null @@ -1,75 +0,0 @@ -// using System.Collections.Generic; -// using System.Linq; -// using NUnit.Framework; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Core.PublishedCache; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Tests.Common.Published; -// using Umbraco.Cms.Tests.UnitTests.TestHelpers; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class PublishContentCacheTests : PublishedSnapshotServiceTestBase -// { -// [SetUp] -// public override void Setup() -// { -// base.Setup(); -// -// var xml = PublishedContentXml.PublishContentCacheTestsXml(); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// // configure the Home content type to be composed of another for tests. -// var compositionType = new ContentType(TestHelper.ShortStringHelper, -1) { Alias = "MyCompositionAlias" }; -// contentTypes.First(x => x.Alias == "Home").AddContentType(compositionType); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// _cache = GetPublishedSnapshot().Content; -// } -// -// private IPublishedContentCache _cache; -// -// [Test] -// public void Has_Content() => Assert.IsTrue(_cache.HasContent()); -// -// [Test] -// public void Get_Root_Docs() -// { -// var result = _cache.GetAtRoot().ToArray(); -// Assert.AreEqual(2, result.Length); -// Assert.AreEqual(1046, result.ElementAt(0).Id); -// Assert.AreEqual(1172, result.ElementAt(1).Id); -// } -// -// [TestCase("/", 1046)] -// [TestCase("/home", 1046)] -// [TestCase("/Home", 1046)] // test different cases -// [TestCase("/home/sub1", 1173)] -// [TestCase("/Home/sub1", 1173)] -// [TestCase("/home/Sub1", 1173)] // test different cases -// [TestCase("/home/Sub'Apostrophe", 1177)] -// public void Get_Node_By_Route(string route, int nodeId) -// { -// var result = _cache.GetByRoute(route, false); -// Assert.IsNotNull(result); -// Assert.AreEqual(nodeId, result.Id); -// } -// -// [TestCase("/", 1046)] -// [TestCase("/sub1", 1173)] -// [TestCase("/Sub1", 1173)] -// public void Get_Node_By_Route_Hiding_Top_Level_Nodes(string route, int nodeId) -// { -// var result = _cache.GetByRoute(route, true); -// Assert.IsNotNull(result); -// Assert.AreEqual(nodeId, result.Id); -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentExtensionTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentExtensionTests.cs deleted file mode 100644 index a86c0d4c226e..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentExtensionTests.cs +++ /dev/null @@ -1,77 +0,0 @@ -// using System.Collections.Generic; -// using System.Linq; -// using NUnit.Framework; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Tests.Common.Published; -// using Umbraco.Cms.Tests.UnitTests.TestHelpers; -// using Umbraco.Extensions; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class PublishedContentExtensionTests : PublishedSnapshotServiceTestBase -// { -// [SetUp] -// public override void Setup() -// { -// base.Setup(); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// XmlContent, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// // configure inheritance for content types -// var baseType = new ContentType(TestHelper.ShortStringHelper, -1) { Alias = "Base" }; -// contentTypes[0].AddContentType(baseType); -// -// InitializedCache(kits, contentTypes, dataTypes); -// } -// -// private const string XmlContent = @" -// -// -// ]> -// -// -// "; -// -// [Test] -// public void IsDocumentType_NonRecursive_ActualType_ReturnsTrue() -// { -// var publishedContent = GetContent(1100); -// Assert.That(publishedContent.IsDocumentType("Inherited", false)); -// } -// -// [Test] -// public void IsDocumentType_NonRecursive_BaseType_ReturnsFalse() -// { -// var publishedContent = GetContent(1100); -// Assert.That(publishedContent.IsDocumentType("Base", false), Is.False); -// } -// -// [Test] -// public void IsDocumentType_Recursive_ActualType_ReturnsTrue() -// { -// var publishedContent = GetContent(1100); -// Assert.That(publishedContent.IsDocumentType("Inherited", true)); -// } -// -// [Test] -// public void IsDocumentType_Recursive_BaseType_ReturnsTrue() -// { -// var publishedContent = GetContent(1100); -// Assert.That(publishedContent.IsDocumentType("Base", true)); -// } -// -// [Test] -// public void IsDocumentType_Recursive_InvalidBaseType_ReturnsFalse() -// { -// var publishedContent = GetContent(1100); -// Assert.That(publishedContent.IsDocumentType("invalidbase", true), Is.False); -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentLanguageVariantTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentLanguageVariantTests.cs deleted file mode 100644 index b6cb73b2a68c..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentLanguageVariantTests.cs +++ /dev/null @@ -1,377 +0,0 @@ -// using System.Collections.Generic; -// using System.Linq; -// using Moq; -// using NUnit.Framework; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Core.Models.PublishedContent; -// using Umbraco.Cms.Core.PropertyEditors; -// using Umbraco.Cms.Core.PropertyEditors.ValueConverters; -// using Umbraco.Cms.Core.Services; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Tests.Common.Builders; -// using Umbraco.Cms.Tests.Common.Builders.Extensions; -// using Umbraco.Cms.Tests.UnitTests.TestHelpers; -// using Umbraco.Extensions; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class PublishedContentLanguageVariantTests : PublishedSnapshotServiceTestBase -// { -// [SetUp] -// public override void Setup() -// { -// base.Setup(); -// -// var dataTypes = GetDefaultDataTypes(); -// var cache = CreateCache(dataTypes, out var contentTypes); -// -// InitializedCache(cache, contentTypes, dataTypes); -// } -// -// protected override PropertyValueConverterCollection PropertyValueConverterCollection -// { -// get -// { -// var collection = base.PropertyValueConverterCollection; -// return new PropertyValueConverterCollection(() => collection.Append(new TestNoValueValueConverter())); -// } -// } -// -// private class TestNoValueValueConverter : SimpleTinyMceValueConverter -// { -// public override bool IsConverter(IPublishedPropertyType propertyType) -// => propertyType.Alias == "noprop"; -// -// // for this test, we return false for IsValue for this property -// public override bool? IsValue(object value, PropertyValueLevel level) => false; -// } -// -// /// -// /// Override to mock localization service -// /// -// /// -// protected override ServiceContext CreateServiceContext(IContentType[] contentTypes, IMediaType[] mediaTypes, IDataType[] dataTypes) -// { -// var serviceContext = base.CreateServiceContext(contentTypes, mediaTypes, dataTypes); -// -// var localizationService = Mock.Get(serviceContext.LocalizationService); -// -// var languages = new List -// { -// new("en-US", "English (United States)") { Id = 1, IsDefault = true }, -// new("fr", "French") { Id = 2 }, -// new("es", "Spanish") { Id = 3, FallbackIsoCode = "en-US" }, -// new("it", "Italian") { Id = 4, FallbackIsoCode = "es" }, -// new("de", "German") { Id = 5 }, -// new Language("da", "Danish") { Id = 6, FallbackIsoCode = "no" }, -// new Language("sv", "Swedish") { Id = 7, FallbackIsoCode = "da" }, -// new Language("no", "Norweigan") { Id = 8, FallbackIsoCode = "sv" }, -// new Language("nl", "Dutch") { Id = 9, FallbackIsoCode = "en-US" }, -// }; -// -// localizationService.Setup(x => x.GetAllLanguages()).Returns(languages); -// localizationService.Setup(x => x.GetLanguageById(It.IsAny())) -// .Returns((int id) => languages.SingleOrDefault(y => y.Id == id)); -// localizationService.Setup(x => x.GetLanguageByIsoCode(It.IsAny())) -// .Returns((string c) => languages.SingleOrDefault(y => y.IsoCode == c)); -// -// return serviceContext; -// } -// -// /// -// /// Creates a content cache -// /// -// /// -// /// -// /// -// /// -// /// Builds a content hierarchy of 3 nodes, each has a different set of cultural properties. -// /// The first 2 share the same content type, the last one is a different content type. -// /// NOTE: The content items themselves are 'Invariant' but their properties are 'Variant' by culture. -// /// Normally in Umbraco this is prohibited but our APIs and database do actually support that behavior. -// /// It is simpler to have these tests run this way, else we would need to use WithCultureInfos -// /// for each item and pass in name values for all cultures we are supporting and then specify the -// /// default VariationContextAccessor.VariationContext value to be a default culture instead of "". -// /// -// private IEnumerable CreateCache(IDataType[] dataTypes, out ContentType[] contentTypes) -// { -// var result = new List(); -// -// var propertyDataTypes = new Dictionary -// { -// // we only have one data type for this test which will be resolved with string empty. -// [string.Empty] = dataTypes[0], -// }; -// -// var contentType1 = new ContentType(ShortStringHelper, -1); -// -// var item1Data = new ContentDataBuilder() -// .WithName("Content 1") -// .WithProperties(new PropertyDataBuilder() -// .WithPropertyData("welcomeText", "Welcome") -// .WithPropertyData("welcomeText", "Welcome", "en-US") -// .WithPropertyData("welcomeText", "Willkommen", "de") -// .WithPropertyData("welcomeText", "Welkom", "nl") -// .WithPropertyData("welcomeText2", "Welcome") -// .WithPropertyData("welcomeText2", "Welcome", "en-US") -// .WithPropertyData("noprop", "xxx") -// .Build()) -// -// // build with a dynamically created content type -// .Build(ShortStringHelper, propertyDataTypes, contentType1, "ContentType1"); -// -// var item1 = ContentNodeKitBuilder.CreateWithContent( -// contentType1.Id, -// 1, -// "-1,1", -// draftData: item1Data, -// publishedData: item1Data); -// -// result.Add(item1); -// -// var item2Data = new ContentDataBuilder() -// .WithName("Content 2") -// .WithProperties(new PropertyDataBuilder() -// .WithPropertyData("welcomeText", "Welcome") -// .WithPropertyData("welcomeText", "Welcome", "en-US") -// .WithPropertyData("numericField", 123) -// .WithPropertyData("numericField", 123, "en-US") -// .WithPropertyData("noprop", "xxx") -// .Build()) -// -// // build while dynamically updating the same content type -// .Build(ShortStringHelper, propertyDataTypes, contentType1); -// -// var item2 = ContentNodeKitBuilder.CreateWithContent( -// contentType1.Id, -// 2, -// "-1,1,2", -// parentContentId: 1, -// draftData: item2Data, -// publishedData: item2Data); -// -// result.Add(item2); -// -// var contentType2 = new ContentType(ShortStringHelper, -1); -// -// var item3Data = new ContentDataBuilder() -// .WithName("Content 3") -// .WithProperties(new PropertyDataBuilder() -// .WithPropertyData("prop3", "Oxxo") -// .WithPropertyData("prop3", "Oxxo", "en-US") -// .Build()) -// -// // build with a dynamically created content type -// .Build(ShortStringHelper, propertyDataTypes, contentType2, "ContentType2"); -// -// var item3 = ContentNodeKitBuilder.CreateWithContent( -// contentType2.Id, -// 3, -// "-1,1,2,3", -// parentContentId: 2, -// draftData: item3Data, -// publishedData: item3Data); -// -// result.Add(item3); -// -// contentTypes = new[] { contentType1, contentType2 }; -// -// return result; -// } -// -// [Test] -// public void Can_Get_Content_For_Populated_Requested_Language() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First(); -// var value = content.Value(Mock.Of(), "welcomeText", "en-US"); -// Assert.AreEqual("Welcome", value); -// } -// -// [Test] -// public void Can_Get_Content_For_Populated_Requested_Non_Default_Language() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First(); -// var value = content.Value(Mock.Of(), "welcomeText", "de"); -// Assert.AreEqual("Willkommen", value); -// } -// -// [Test] -// public void Do_Not_Get_Content_For_Unpopulated_Requested_Language_Without_Fallback() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First(); -// var value = content.Value(Mock.Of(), "welcomeText", "fr"); -// Assert.IsNull(value); -// } -// -// [Test] -// public void Do_Not_Get_Content_For_Unpopulated_Requested_Language_With_Fallback_Unless_Requested() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First(); -// var value = content.Value(Mock.Of(), "welcomeText", "es"); -// Assert.IsNull(value); -// } -// -// [Test] -// public void Can_Get_Content_For_Unpopulated_Requested_Language_With_Fallback() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First(); -// var value = content.Value(PublishedValueFallback, "welcomeText", "es", fallback: Fallback.ToLanguage); -// Assert.AreEqual("Welcome", value); -// } -// -// [Test] -// public void Can_Get_Content_For_Unpopulated_Requested_Language_With_Fallback_Over_Two_Levels() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First(); -// var value = content.Value(PublishedValueFallback, "welcomeText", "it", fallback: Fallback.To(Fallback.Language, Fallback.Ancestors)); -// Assert.AreEqual("Welcome", value); -// } -// -// [Test] -// public void Do_Not_GetContent_For_Unpopulated_Requested_Language_With_Fallback_Over_That_Loops() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First(); -// var value = content.Value(Mock.Of(), "welcomeText", "no", fallback: Fallback.ToLanguage); -// Assert.IsNull(value); -// } -// -// [Test] -// public void Can_Get_Content_For_Unpopulated_Requested_DefaultLanguage_With_Fallback() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First(); -// var value = content.Value(PublishedValueFallback, "welcomeText", "fr", fallback: Fallback.ToDefaultLanguage); -// Assert.AreEqual("Welcome", value); -// } -// -// [Test] -// public void Do_Not_Get_Content_Recursively_Unless_Requested() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First().Children.First(); -// var value = content.Value(Mock.Of(), "welcomeText2"); -// Assert.IsNull(value); -// } -// -// [Test] -// public void Can_Get_Content_Recursively() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First().Children.First(); -// var value = content.Value(PublishedValueFallback, "welcomeText2", fallback: Fallback.ToAncestors); -// Assert.AreEqual("Welcome", value); -// } -// -// [Test] -// public void Do_Not_Get_Content_Recursively_Unless_Requested2() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First().Children.First().Children.First(); -// Assert.IsNull(content.GetProperty("welcomeText2")); -// var value = content.Value(Mock.Of(), "welcomeText2"); -// Assert.IsNull(value); -// } -// -// [Test] -// public void Can_Get_Content_Recursively2() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First().Children.First().Children.First(); -// Assert.IsNull(content.GetProperty("welcomeText2")); -// var value = content.Value(PublishedValueFallback, "welcomeText2", fallback: Fallback.ToAncestors); -// Assert.AreEqual("Welcome", value); -// } -// -// [Test] -// public void Can_Get_Content_Recursively3() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First().Children.First().Children.First(); -// Assert.IsNull(content.GetProperty("noprop")); -// var value = content.Value(PublishedValueFallback, "noprop", fallback: Fallback.ToAncestors); -// -// // property has no value - based on the converter -// // but we still get the value (ie, the converter would do something) -// Assert.AreEqual("xxx", value.ToString()); -// } -// -// [Test] -// public void Can_Get_Content_With_Recursive_Priority() -// { -// VariationContextAccessor.VariationContext = new VariationContext("nl"); -// -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First().Children.First(); -// -// var value = content.Value(PublishedValueFallback, "welcomeText", "nl", fallback: Fallback.To(Fallback.Ancestors, Fallback.Language)); -// -// // No Dutch value is directly assigned. Check has fallen back to Dutch value from parent. -// Assert.AreEqual("Welkom", value); -// } -// -// [Test] -// public void Can_Get_Content_With_Fallback_Language_Priority() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First().Children.First(); -// -// var value = content.Value(PublishedValueFallback, "welcomeText", "nl", fallback: Fallback.ToLanguage); -// var numericValue = content.Value(PublishedValueFallback, "numericField", "nl", fallback: Fallback.ToLanguage); -// -// // No Dutch value is directly assigned. Check has fallen back to English value from language variant. -// Assert.AreEqual("Welcome", value); -// Assert.AreEqual(123, numericValue); -// } -// -// [Test] -// public void Can_Get_Content_For_Property_With_Fallback_Language_Priority() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First().Children.First(); -// -// var value = content.GetProperty("welcomeText")!.Value(PublishedValueFallback, "nl", fallback: Fallback.ToLanguage); -// var numericValue = content.GetProperty("numericField")!.Value(PublishedValueFallback, "nl", fallback: Fallback.ToLanguage); -// -// // No Dutch value is directly assigned. Check has fallen back to English value from language variant. -// Assert.AreEqual("Welcome", value); -// Assert.AreEqual(123, numericValue); -// } -// -// [Test] -// public void Throws_For_Non_Supported_Fallback() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First().Children.First(); -// -// Assert.Throws(() => -// content.Value(PublishedValueFallback, "welcomeText", "nl", fallback: Fallback.To(999))); -// } -// -// [Test] -// public void Can_Fallback_To_Default_Value() -// { -// var snapshot = GetPublishedSnapshot(); -// var content = snapshot.Content.GetAtRoot().First().Children.First(); -// -// // no Dutch value is assigned, so getting null -// var value = content.Value(PublishedValueFallback, "welcomeText", "nl"); -// Assert.IsNull(value); -// -// // even if we 'just' provide a default value -// value = content.Value(PublishedValueFallback, "welcomeText", "nl", defaultValue: "woop"); -// Assert.IsNull(value); -// -// // but it works with proper fallback settings -// value = content.Value(PublishedValueFallback, "welcomeText", "nl", fallback: Fallback.ToDefaultValue, defaultValue: "woop"); -// Assert.AreEqual("woop", value); -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentTests.cs deleted file mode 100644 index 15d55e6d21b2..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedContentTests.cs +++ /dev/null @@ -1,971 +0,0 @@ -// using System.Collections.Generic; -// using System.Linq; -// using Moq; -// using NUnit.Framework; -// using Umbraco.Cms.Core; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Core.Models.PublishedContent; -// using Umbraco.Cms.Core.PropertyEditors; -// using Umbraco.Cms.Core.PublishedCache; -// using Umbraco.Cms.Core.Strings; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Tests.Common.Published; -// using Umbraco.Cms.Tests.UnitTests.TestHelpers; -// using Umbraco.Extensions; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class PublishedContentTests : PublishedSnapshotServiceTestBase -// { -// [SetUp] -// public override void Setup() -// { -// base.Setup(); -// -// var xml = PublishedContentXml.PublishedContentTestXml(1234, _node1173Guid); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// _dataTypes = dataTypes; -// -// // configure the Home content type to be composed of another for tests. -// var compositionType = new ContentType(TestHelper.ShortStringHelper, -1) { Alias = "MyCompositionAlias" }; -// contentTypes.First(x => x.Alias == "Home").AddContentType(compositionType); -// -// InitializedCache(kits, contentTypes, dataTypes); -// } -// -// private readonly Guid _node1173Guid = Guid.NewGuid(); -// private PublishedModelFactory _publishedModelFactory; -// private DataType[] _dataTypes; -// -// // override to specify our own factory with custom types -// protected override IPublishedModelFactory PublishedModelFactory -// => _publishedModelFactory ??= new PublishedModelFactory( -// new[] { typeof(Home), typeof(Anything), typeof(CustomDocument) }, -// PublishedValueFallback); -// -// [PublishedModel("Home")] -// internal class Home : PublishedContentModel -// { -// public Home(IPublishedContent content, IPublishedValueFallback fallback) -// : base(content, fallback) -// { -// } -// -// public bool UmbracoNaviHide => this.Value(Mock.Of(), "umbracoNaviHide"); -// } -// -// [PublishedModel("anything")] -// internal class Anything : PublishedContentModel -// { -// public Anything(IPublishedContent content, IPublishedValueFallback fallback) -// : base(content, fallback) -// { -// } -// } -// -// [PublishedModel("CustomDocument")] -// internal class CustomDocument : PublishedContentModel -// { -// public CustomDocument(IPublishedContent content, IPublishedValueFallback fallback) -// : base(content, fallback) -// { -// } -// } -// -// [Test] -// public void GetNodeByIds() -// { -// var snapshot = GetPublishedSnapshot(); -// -// var contentById = snapshot.Content.GetById(1173); -// Assert.IsNotNull(contentById); -// var contentByGuid = snapshot.Content.GetById(_node1173Guid); -// Assert.IsNotNull(contentByGuid); -// Assert.AreEqual(contentById.Id, contentByGuid.Id); -// Assert.AreEqual(contentById.Key, contentByGuid.Key); -// -// contentById = snapshot.Content.GetById(666); -// Assert.IsNull(contentById); -// contentByGuid = snapshot.Content.GetById(Guid.NewGuid()); -// Assert.IsNull(contentByGuid); -// } -// -// [Test] -// public void Is_Last_From_Where_Filter_Dynamic_Linq() -// { -// var doc = GetContent(1173); -// -// var items = doc.Children(VariationContextAccessor).Where(x => x.IsVisible(Mock.Of())) -// .ToIndexedArray(); -// -// foreach (var item in items) -// { -// if (item.Content.Id != 1178) -// { -// Assert.IsFalse(item.IsLast(), $"The item {item.Content.Id} is last"); -// } -// else -// { -// Assert.IsTrue(item.IsLast(), $"The item {item.Content.Id} is not last"); -// } -// } -// } -// -// [Test] -// public void Is_Last_From_Where_Filter() -// { -// var doc = GetContent(1173); -// -// var items = doc -// .Children(VariationContextAccessor) -// .Where(x => x.IsVisible(Mock.Of())) -// .ToIndexedArray(); -// -// Assert.AreEqual(4, items.Length); -// -// foreach (var d in items) -// { -// switch (d.Content.Id) -// { -// case 1174: -// Assert.IsTrue(d.IsFirst()); -// Assert.IsFalse(d.IsLast()); -// break; -// case 117: -// Assert.IsFalse(d.IsFirst()); -// Assert.IsFalse(d.IsLast()); -// break; -// case 1177: -// Assert.IsFalse(d.IsFirst()); -// Assert.IsFalse(d.IsLast()); -// break; -// case 1178: -// Assert.IsFalse(d.IsFirst()); -// Assert.IsTrue(d.IsLast()); -// break; -// default: -// Assert.Fail("Invalid id."); -// break; -// } -// } -// } -// -// [Test] -// public void Is_Last_From_Where_Filter2() -// { -// var doc = GetContent(1173); -// var ct = doc.ContentType; -// -// var items = doc.Children(VariationContextAccessor) -// .Select(x => x.CreateModel(PublishedModelFactory)) // linq, returns IEnumerable -// -// // only way around this is to make sure every IEnumerable extension -// // explicitely returns a PublishedContentSet, not an IEnumerable -// .OfType() // ours, return IEnumerable (actually a PublishedContentSet) -// .Where(x => x.IsVisible(Mock.Of())) // so, here it's linq again :-( -// .ToIndexedArray(); // so, we need that one for the test to pass -// -// Assert.AreEqual(1, items.Length); -// -// foreach (var d in items) -// { -// switch (d.Content.Id) -// { -// case 1174: -// Assert.IsTrue(d.IsFirst()); -// Assert.IsTrue(d.IsLast()); -// break; -// default: -// Assert.Fail("Invalid id."); -// break; -// } -// } -// } -// -// [Test] -// public void Is_Last_From_Take() -// { -// var doc = GetContent(1173); -// -// var items = doc.Children(VariationContextAccessor).Take(4).ToIndexedArray(); -// -// foreach (var item in items) -// { -// if (item.Content.Id != 1178) -// { -// Assert.IsFalse(item.IsLast()); -// } -// else -// { -// Assert.IsTrue(item.IsLast()); -// } -// } -// } -// -// [Test] -// public void Is_Last_From_Skip() -// { -// var doc = GetContent(1173); -// -// foreach (var d in doc.Children(VariationContextAccessor).Skip(1).ToIndexedArray()) -// { -// if (d.Content.Id != 1176) -// { -// Assert.IsFalse(d.IsLast()); -// } -// else -// { -// Assert.IsTrue(d.IsLast()); -// } -// } -// } -// -// [Test] -// public void Is_Last_From_Concat() -// { -// var doc = GetContent(1173); -// -// var items = doc.Children(VariationContextAccessor) -// .Concat(new[] { GetContent(1175), GetContent(4444) }) -// .ToIndexedArray(); -// -// foreach (var item in items) -// { -// if (item.Content.Id != 4444) -// { -// Assert.IsFalse(item.IsLast()); -// } -// else -// { -// Assert.IsTrue(item.IsLast()); -// } -// } -// } -// -// [Test] -// public void Descendants_Ordered_Properly() -// { -// var doc = GetContent(1046); -// -// var expected = new[] { 1046, 1173, 1174, 117, 1177, 1178, 1179, 1176, 1175, 4444, 1172 }; -// var exindex = 0; -// -// // must respect the XPath descendants-or-self axis! -// foreach (var d in doc.DescendantsOrSelf(Mock.Of())) -// { -// Assert.AreEqual(expected[exindex++], d.Id); -// } -// } -// -// [Test] -// public void Get_Property_Value_Recursive() -// { -// // TODO: We need to use a different fallback? -// var doc = GetContent(1174); -// var rVal = doc.Value(PublishedValueFallback, "testRecursive", fallback: Fallback.ToAncestors); -// var nullVal = doc.Value(PublishedValueFallback, "DoNotFindThis", fallback: Fallback.ToAncestors); -// Assert.AreEqual("This is the recursive val", rVal); -// Assert.AreEqual(null, nullVal); -// } -// -// [Test] -// public void Get_Property_Value_Uses_Converter() -// { -// var doc = GetContent(1173); -// -// var propVal = doc.Value(PublishedValueFallback, "content"); -// Assert.IsInstanceOf(typeof(IHtmlEncodedString), propVal); -// Assert.AreEqual("
This is some content
", propVal.ToString()); -// -// var propVal2 = doc.Value(PublishedValueFallback, "content"); -// Assert.IsInstanceOf(typeof(IHtmlEncodedString), propVal2); -// Assert.AreEqual("
This is some content
", propVal2.ToString()); -// -// var propVal3 = doc.Value(PublishedValueFallback, "Content"); -// Assert.IsInstanceOf(typeof(IHtmlEncodedString), propVal3); -// Assert.AreEqual("
This is some content
", propVal3.ToString()); -// } -// -// [Test] -// public void Complex_Linq() -// { -// var doc = GetContent(1173); -// -// var result = doc.Ancestors().OrderBy(x => x.Level) -// .Single() -// .Descendants(Mock.Of()) -// .FirstOrDefault(x => -// x.Value(PublishedValueFallback, "selectedNodes", fallback: Fallback.ToDefaultValue, defaultValue: string.Empty).Split(',').Contains("1173")); -// -// Assert.IsNotNull(result); -// } -// -// [Test] -// public void Children_GroupBy_DocumentTypeAlias() -// { -// // var home = new AutoPublishedContentType(Guid.NewGuid(), 22, "Home", new PublishedPropertyType[] { }); -// // var custom = new AutoPublishedContentType(Guid.NewGuid(), 23, "CustomDocument", new PublishedPropertyType[] { }); -// // var contentTypes = new Dictionary -// // { -// // { home.Alias, home }, -// // { custom.Alias, custom } -// // }; -// // ContentTypesCache.GetPublishedContentTypeByAlias = alias => contentTypes[alias]; -// var doc = GetContent(1046); -// -// var found1 = doc.Children(VariationContextAccessor).GroupBy(x => x.ContentType.Alias).ToArray(); -// -// Assert.AreEqual(2, found1.Length); -// Assert.AreEqual(2, found1.Single(x => x.Key.ToString() == "Home").Count()); -// Assert.AreEqual(1, found1.Single(x => x.Key.ToString() == "CustomDocument").Count()); -// } -// -// [Test] -// public void Children_Where_DocumentTypeAlias() -// { -// // var home = new AutoPublishedContentType(Guid.NewGuid(), 22, "Home", new PublishedPropertyType[] { }); -// // var custom = new AutoPublishedContentType(Guid.NewGuid(), 23, "CustomDocument", new PublishedPropertyType[] { }); -// // var contentTypes = new Dictionary -// // { -// // { home.Alias, home }, -// // { custom.Alias, custom } -// // }; -// // ContentTypesCache.GetPublishedContentTypeByAlias = alias => contentTypes[alias]; -// var doc = GetContent(1046); -// -// var found1 = doc.Children(VariationContextAccessor).Where(x => x.ContentType.Alias == "CustomDocument"); -// var found2 = doc.Children(VariationContextAccessor).Where(x => x.ContentType.Alias == "Home"); -// -// Assert.AreEqual(1, found1.Count()); -// Assert.AreEqual(2, found2.Count()); -// } -// -// [Test] -// public void Children_Order_By_Update_Date() -// { -// var doc = GetContent(1173); -// -// var ordered = doc.Children(VariationContextAccessor).OrderBy(x => x.UpdateDate); -// -// var correctOrder = new[] { 1178, 1177, 1174, 1176 }; -// for (var i = 0; i < correctOrder.Length; i++) -// { -// Assert.AreEqual(correctOrder[i], ordered.ElementAt(i).Id); -// } -// } -// -// [Test] -// public void FirstChild() -// { -// var doc = GetContent(1173); // has child nodes -// Assert.IsNotNull(doc.FirstChild(Mock.Of())); -// Assert.IsNotNull(doc.FirstChild(Mock.Of(), x => true)); -// Assert.IsNotNull(doc.FirstChild(Mock.Of())); -// -// doc = GetContent(1175); // does not have child nodes -// Assert.IsNull(doc.FirstChild(Mock.Of())); -// Assert.IsNull(doc.FirstChild(Mock.Of(), x => true)); -// Assert.IsNull(doc.FirstChild(Mock.Of())); -// } -// -// [Test] -// public void FirstChildAsT() -// { -// var doc = GetContent(1046); // has child nodes -// -// var model = doc.FirstChild(Mock.Of(), x => true); // predicate -// -// Assert.IsNotNull(model); -// Assert.IsTrue(model.Id == 1173); -// Assert.IsInstanceOf(model); -// Assert.IsInstanceOf(model); -// -// doc = GetContent(1175); // does not have child nodes -// Assert.IsNull(doc.FirstChild(Mock.Of())); -// Assert.IsNull(doc.FirstChild(Mock.Of(), x => true)); -// } -// -// [Test] -// public void IsComposedOf() -// { -// var doc = GetContent(1173); -// -// var isComposedOf = doc.IsComposedOf("MyCompositionAlias"); -// -// Assert.IsTrue(isComposedOf); -// } -// -// [Test] -// public void HasProperty() -// { -// var doc = GetContent(1173); -// -// var hasProp = doc.HasProperty(Constants.Conventions.Content.UrlAlias); -// -// Assert.IsTrue(hasProp); -// } -// -// [Test] -// public void HasValue() -// { -// var doc = GetContent(1173); -// -// var hasValue = doc.HasValue(Mock.Of(), Constants.Conventions.Content.UrlAlias); -// var noValue = doc.HasValue(Mock.Of(), "blahblahblah"); -// -// Assert.IsTrue(hasValue); -// Assert.IsFalse(noValue); -// } -// -// [Test] -// public void Ancestors_Where_Visible() -// { -// var doc = GetContent(1174); -// -// var whereVisible = doc.Ancestors().Where(x => x.IsVisible(Mock.Of())); -// Assert.AreEqual(1, whereVisible.Count()); -// } -// -// [Test] -// public void Visible() -// { -// var hidden = GetContent(1046); -// var visible = GetContent(1173); -// -// Assert.IsFalse(hidden.IsVisible(Mock.Of())); -// Assert.IsTrue(visible.IsVisible(Mock.Of())); -// } -// -// [Test] -// public void Ancestor_Or_Self() -// { -// var doc = GetContent(1173); -// -// var result = doc.AncestorOrSelf(); -// -// Assert.IsNotNull(result); -// -// // ancestor-or-self has to be self! -// Assert.AreEqual(1173, result.Id); -// } -// -// [Test] -// public void U4_4559() -// { -// var doc = GetContent(1174); -// var result = doc.AncestorOrSelf(1); -// Assert.IsNotNull(result); -// Assert.AreEqual(1046, result.Id); -// } -// -// [Test] -// public void Ancestors_Or_Self() -// { -// var doc = GetContent(1174); -// -// var result = doc.AncestorsOrSelf().ToArray(); -// -// Assert.IsNotNull(result); -// -// Assert.AreEqual(3, result.Length); -// Assert.IsTrue(result.Select(x => x.Id).ContainsAll(new[] { 1174, 1173, 1046 })); -// } -// -// [Test] -// public void Ancestors() -// { -// var doc = GetContent(1174); -// -// var result = doc.Ancestors().ToArray(); -// -// Assert.IsNotNull(result); -// -// Assert.AreEqual(2, result.Length); -// Assert.IsTrue(result.Select(x => x.Id).ContainsAll(new[] { 1173, 1046 })); -// } -// -// [Test] -// public void IsAncestor() -// { -// // Structure: -// // - Root : 1046 (no parent) -// // -- Home: 1173 (parent 1046) -// // -- Custom Doc: 1178 (parent 1173) -// // --- Custom Doc2: 1179 (parent: 1178) -// // -- Custom Doc4: 117 (parent 1173) -// // - Custom Doc3: 1172 (no parent) -// var home = GetContent(1173); -// var root = GetContent(1046); -// var customDoc = GetContent(1178); -// var customDoc2 = GetContent(1179); -// var customDoc3 = GetContent(1172); -// var customDoc4 = GetContent(117); -// -// Assert.IsTrue(root.IsAncestor(customDoc4)); -// Assert.IsFalse(root.IsAncestor(customDoc3)); -// Assert.IsTrue(root.IsAncestor(customDoc2)); -// Assert.IsTrue(root.IsAncestor(customDoc)); -// Assert.IsTrue(root.IsAncestor(home)); -// Assert.IsFalse(root.IsAncestor(root)); -// -// Assert.IsTrue(home.IsAncestor(customDoc4)); -// Assert.IsFalse(home.IsAncestor(customDoc3)); -// Assert.IsTrue(home.IsAncestor(customDoc2)); -// Assert.IsTrue(home.IsAncestor(customDoc)); -// Assert.IsFalse(home.IsAncestor(home)); -// Assert.IsFalse(home.IsAncestor(root)); -// -// Assert.IsFalse(customDoc.IsAncestor(customDoc4)); -// Assert.IsFalse(customDoc.IsAncestor(customDoc3)); -// Assert.IsTrue(customDoc.IsAncestor(customDoc2)); -// Assert.IsFalse(customDoc.IsAncestor(customDoc)); -// Assert.IsFalse(customDoc.IsAncestor(home)); -// Assert.IsFalse(customDoc.IsAncestor(root)); -// -// Assert.IsFalse(customDoc2.IsAncestor(customDoc4)); -// Assert.IsFalse(customDoc2.IsAncestor(customDoc3)); -// Assert.IsFalse(customDoc2.IsAncestor(customDoc2)); -// Assert.IsFalse(customDoc2.IsAncestor(customDoc)); -// Assert.IsFalse(customDoc2.IsAncestor(home)); -// Assert.IsFalse(customDoc2.IsAncestor(root)); -// -// Assert.IsFalse(customDoc3.IsAncestor(customDoc3)); -// } -// -// [Test] -// public void IsAncestorOrSelf() -// { -// // Structure: -// // - Root : 1046 (no parent) -// // -- Home: 1173 (parent 1046) -// // -- Custom Doc: 1178 (parent 1173) -// // --- Custom Doc2: 1179 (parent: 1178) -// // -- Custom Doc4: 117 (parent 1173) -// // - Custom Doc3: 1172 (no parent) -// var home = GetContent(1173); -// var root = GetContent(1046); -// var customDoc = GetContent(1178); -// var customDoc2 = GetContent(1179); -// var customDoc3 = GetContent(1172); -// var customDoc4 = GetContent(117); -// -// Assert.IsTrue(root.IsAncestorOrSelf(customDoc4)); -// Assert.IsFalse(root.IsAncestorOrSelf(customDoc3)); -// Assert.IsTrue(root.IsAncestorOrSelf(customDoc2)); -// Assert.IsTrue(root.IsAncestorOrSelf(customDoc)); -// Assert.IsTrue(root.IsAncestorOrSelf(home)); -// Assert.IsTrue(root.IsAncestorOrSelf(root)); -// -// Assert.IsTrue(home.IsAncestorOrSelf(customDoc4)); -// Assert.IsFalse(home.IsAncestorOrSelf(customDoc3)); -// Assert.IsTrue(home.IsAncestorOrSelf(customDoc2)); -// Assert.IsTrue(home.IsAncestorOrSelf(customDoc)); -// Assert.IsTrue(home.IsAncestorOrSelf(home)); -// Assert.IsFalse(home.IsAncestorOrSelf(root)); -// -// Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc4)); -// Assert.IsFalse(customDoc.IsAncestorOrSelf(customDoc3)); -// Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc2)); -// Assert.IsTrue(customDoc.IsAncestorOrSelf(customDoc)); -// Assert.IsFalse(customDoc.IsAncestorOrSelf(home)); -// Assert.IsFalse(customDoc.IsAncestorOrSelf(root)); -// -// Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc4)); -// Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc3)); -// Assert.IsTrue(customDoc2.IsAncestorOrSelf(customDoc2)); -// Assert.IsFalse(customDoc2.IsAncestorOrSelf(customDoc)); -// Assert.IsFalse(customDoc2.IsAncestorOrSelf(home)); -// Assert.IsFalse(customDoc2.IsAncestorOrSelf(root)); -// -// Assert.IsTrue(customDoc4.IsAncestorOrSelf(customDoc4)); -// Assert.IsTrue(customDoc3.IsAncestorOrSelf(customDoc3)); -// } -// -// [Test] -// public void Descendants_Or_Self() -// { -// var doc = GetContent(1046); -// -// var result = doc.DescendantsOrSelf(Mock.Of()).ToArray(); -// -// Assert.IsNotNull(result); -// -// Assert.AreEqual(10, result.Count()); -// Assert.IsTrue(result.Select(x => x.Id).ContainsAll(new[] { 1046, 1173, 1174, 1176, 1175 })); -// } -// -// [Test] -// public void Descendants() -// { -// var doc = GetContent(1046); -// -// var result = doc.Descendants(Mock.Of()).ToArray(); -// -// Assert.IsNotNull(result); -// -// Assert.AreEqual(9, result.Count()); -// Assert.IsTrue(result.Select(x => x.Id).ContainsAll(new[] { 1173, 1174, 1176, 1175, 4444 })); -// } -// -// [Test] -// public void IsDescendant() -// { -// // Structure: -// // - Root : 1046 (no parent) -// // -- Home: 1173 (parent 1046) -// // -- Custom Doc: 1178 (parent 1173) -// // --- Custom Doc2: 1179 (parent: 1178) -// // -- Custom Doc4: 117 (parent 1173) -// // - Custom Doc3: 1172 (no parent) -// var home = GetContent(1173); -// var root = GetContent(1046); -// var customDoc = GetContent(1178); -// var customDoc2 = GetContent(1179); -// var customDoc3 = GetContent(1172); -// var customDoc4 = GetContent(117); -// -// Assert.IsFalse(root.IsDescendant(root)); -// Assert.IsFalse(root.IsDescendant(home)); -// Assert.IsFalse(root.IsDescendant(customDoc)); -// Assert.IsFalse(root.IsDescendant(customDoc2)); -// Assert.IsFalse(root.IsDescendant(customDoc3)); -// Assert.IsFalse(root.IsDescendant(customDoc4)); -// -// Assert.IsTrue(home.IsDescendant(root)); -// Assert.IsFalse(home.IsDescendant(home)); -// Assert.IsFalse(home.IsDescendant(customDoc)); -// Assert.IsFalse(home.IsDescendant(customDoc2)); -// Assert.IsFalse(home.IsDescendant(customDoc3)); -// Assert.IsFalse(home.IsDescendant(customDoc4)); -// -// Assert.IsTrue(customDoc.IsDescendant(root)); -// Assert.IsTrue(customDoc.IsDescendant(home)); -// Assert.IsFalse(customDoc.IsDescendant(customDoc)); -// Assert.IsFalse(customDoc.IsDescendant(customDoc2)); -// Assert.IsFalse(customDoc.IsDescendant(customDoc3)); -// Assert.IsFalse(customDoc.IsDescendant(customDoc4)); -// -// Assert.IsTrue(customDoc2.IsDescendant(root)); -// Assert.IsTrue(customDoc2.IsDescendant(home)); -// Assert.IsTrue(customDoc2.IsDescendant(customDoc)); -// Assert.IsFalse(customDoc2.IsDescendant(customDoc2)); -// Assert.IsFalse(customDoc2.IsDescendant(customDoc3)); -// Assert.IsFalse(customDoc2.IsDescendant(customDoc4)); -// -// Assert.IsFalse(customDoc3.IsDescendant(customDoc3)); -// } -// -// [Test] -// public void IsDescendantOrSelf() -// { -// // Structure: -// // - Root : 1046 (no parent) -// // -- Home: 1173 (parent 1046) -// // -- Custom Doc: 1178 (parent 1173) -// // --- Custom Doc2: 1179 (parent: 1178) -// // -- Custom Doc4: 117 (parent 1173) -// // - Custom Doc3: 1172 (no parent) -// var home = GetContent(1173); -// var root = GetContent(1046); -// var customDoc = GetContent(1178); -// var customDoc2 = GetContent(1179); -// var customDoc3 = GetContent(1172); -// var customDoc4 = GetContent(117); -// -// Assert.IsTrue(root.IsDescendantOrSelf(root)); -// Assert.IsFalse(root.IsDescendantOrSelf(home)); -// Assert.IsFalse(root.IsDescendantOrSelf(customDoc)); -// Assert.IsFalse(root.IsDescendantOrSelf(customDoc2)); -// Assert.IsFalse(root.IsDescendantOrSelf(customDoc3)); -// Assert.IsFalse(root.IsDescendantOrSelf(customDoc4)); -// -// Assert.IsTrue(home.IsDescendantOrSelf(root)); -// Assert.IsTrue(home.IsDescendantOrSelf(home)); -// Assert.IsFalse(home.IsDescendantOrSelf(customDoc)); -// Assert.IsFalse(home.IsDescendantOrSelf(customDoc2)); -// Assert.IsFalse(home.IsDescendantOrSelf(customDoc3)); -// Assert.IsFalse(home.IsDescendantOrSelf(customDoc4)); -// -// Assert.IsTrue(customDoc.IsDescendantOrSelf(root)); -// Assert.IsTrue(customDoc.IsDescendantOrSelf(home)); -// Assert.IsTrue(customDoc.IsDescendantOrSelf(customDoc)); -// Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc2)); -// Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc3)); -// Assert.IsFalse(customDoc.IsDescendantOrSelf(customDoc4)); -// -// Assert.IsTrue(customDoc2.IsDescendantOrSelf(root)); -// Assert.IsTrue(customDoc2.IsDescendantOrSelf(home)); -// Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc)); -// Assert.IsTrue(customDoc2.IsDescendantOrSelf(customDoc2)); -// Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc3)); -// Assert.IsFalse(customDoc2.IsDescendantOrSelf(customDoc4)); -// -// Assert.IsTrue(customDoc3.IsDescendantOrSelf(customDoc3)); -// } -// -// [Test] -// public void SiblingsAndSelf() -// { -// // Structure: -// // - Root : 1046 (no parent) -// // -- Level1.1: 1173 (parent 1046) -// // --- Level1.1.1: 1174 (parent 1173) -// // --- Level1.1.2: 117 (parent 1173) -// // --- Level1.1.3: 1177 (parent 1173) -// // --- Level1.1.4: 1178 (parent 1173) -// // ---- Level1.1.4.1: 1179 (parent 1178) -// // --- Level1.1.5: 1176 (parent 1173) -// // -- Level1.2: 1175 (parent 1046) -// // -- Level1.3: 4444 (parent 1046) -// // - Root : 1172 (no parent) -// var root = GetContent(1046); -// var level1_1 = GetContent(1173); -// var level1_1_1 = GetContent(1174); -// var level1_1_2 = GetContent(117); -// var level1_1_3 = GetContent(1177); -// var level1_1_4 = GetContent(1178); -// var level1_1_5 = GetContent(1176); -// var level1_2 = GetContent(1175); -// var level1_3 = GetContent(4444); -// var root2 = GetContent(1172); -// -// var publishedSnapshot = GetPublishedSnapshot(); -// -// CollectionAssertAreEqual(new[] { root, root2 }, root.SiblingsAndSelf(publishedSnapshot, VariationContextAccessor)); -// -// CollectionAssertAreEqual(new[] { level1_1, level1_2, level1_3 }, level1_1.SiblingsAndSelf(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1, level1_2, level1_3 }, level1_2.SiblingsAndSelf(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1, level1_2, level1_3 }, level1_3.SiblingsAndSelf(publishedSnapshot, VariationContextAccessor)); -// -// CollectionAssertAreEqual(new[] { level1_1_1, level1_1_2, level1_1_3, level1_1_4, level1_1_5 }, level1_1_1.SiblingsAndSelf(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1_1, level1_1_2, level1_1_3, level1_1_4, level1_1_5 }, level1_1_2.SiblingsAndSelf(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1_1, level1_1_2, level1_1_3, level1_1_4, level1_1_5 }, level1_1_3.SiblingsAndSelf(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1_1, level1_1_2, level1_1_3, level1_1_4, level1_1_5 }, level1_1_4.SiblingsAndSelf(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1_1, level1_1_2, level1_1_3, level1_1_4, level1_1_5 }, level1_1_5.SiblingsAndSelf(publishedSnapshot, VariationContextAccessor)); -// } -// -// [Test] -// public void Siblings() -// { -// // Structure: -// // - Root : 1046 (no parent) -// // -- Level1.1: 1173 (parent 1046) -// // --- Level1.1.1: 1174 (parent 1173) -// // --- Level1.1.2: 117 (parent 1173) -// // --- Level1.1.3: 1177 (parent 1173) -// // --- Level1.1.4: 1178 (parent 1173) -// // ---- Level1.1.4.1: 1179 (parent 1178) -// // --- Level1.1.5: 1176 (parent 1173) -// // -- Level1.2: 1175 (parent 1046) -// // -- Level1.3: 4444 (parent 1046) -// // - Root : 1172 (no parent) -// var root = GetContent(1046); -// var level1_1 = GetContent(1173); -// var level1_1_1 = GetContent(1174); -// var level1_1_2 = GetContent(117); -// var level1_1_3 = GetContent(1177); -// var level1_1_4 = GetContent(1178); -// var level1_1_5 = GetContent(1176); -// var level1_2 = GetContent(1175); -// var level1_3 = GetContent(4444); -// var root2 = GetContent(1172); -// -// var publishedSnapshot = GetPublishedSnapshot(); -// -// CollectionAssertAreEqual(new[] { root2 }, root.Siblings(publishedSnapshot, VariationContextAccessor)); -// -// CollectionAssertAreEqual(new[] { level1_2, level1_3 }, level1_1.Siblings(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1, level1_3 }, level1_2.Siblings(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1, level1_2 }, level1_3.Siblings(publishedSnapshot, VariationContextAccessor)); -// -// CollectionAssertAreEqual(new[] { level1_1_2, level1_1_3, level1_1_4, level1_1_5 }, level1_1_1.Siblings(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1_1, level1_1_3, level1_1_4, level1_1_5 }, level1_1_2.Siblings(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1_1, level1_1_2, level1_1_4, level1_1_5 }, level1_1_3.Siblings(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1_1, level1_1_2, level1_1_3, level1_1_5 }, level1_1_4.Siblings(publishedSnapshot, VariationContextAccessor)); -// CollectionAssertAreEqual(new[] { level1_1_1, level1_1_2, level1_1_3, level1_1_4 }, level1_1_5.Siblings(publishedSnapshot, VariationContextAccessor)); -// } -// -// private void CollectionAssertAreEqual(IEnumerable expected, IEnumerable actual) -// where T : IPublishedContent -// { -// var e = expected.Select(x => x.Id).ToArray(); -// var a = actual.Select(x => x.Id).ToArray(); -// CollectionAssert.AreEquivalent(e, a, $"\nExpected:\n{string.Join(", ", e)}\n\nActual:\n{string.Join(", ", a)}"); -// } -// -// [Test] -// public void FragmentProperty() -// { -// IEnumerable CreatePropertyTypes(IPublishedContentType contentType) -// { -// yield return PublishedContentTypeFactory.CreatePropertyType(contentType, "detached", _dataTypes[0].Id); -// } -// -// var ct = PublishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 0, "alias", CreatePropertyTypes); -// var pt = ct.GetPropertyType("detached"); -// var prop = new PublishedElementPropertyBase(pt, null, false, PropertyCacheLevel.None, 5548); -// Assert.IsInstanceOf(prop.GetValue()); -// Assert.AreEqual(5548, prop.GetValue()); -// } -// -// [Test] -// public void Fragment2() -// { -// IEnumerable CreatePropertyTypes(IPublishedContentType contentType) -// { -// yield return PublishedContentTypeFactory.CreatePropertyType(contentType, "legend", _dataTypes[0].Id); -// yield return PublishedContentTypeFactory.CreatePropertyType(contentType, "image", _dataTypes[0].Id); -// yield return PublishedContentTypeFactory.CreatePropertyType(contentType, "size", _dataTypes[0].Id); -// } -// -// const string val1 = "boom bam"; -// const int val2 = 0; -// const int val3 = 666; -// -// var guid = Guid.NewGuid(); -// -// var ct = PublishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 0, "alias", CreatePropertyTypes); -// -// var c = new ImageWithLegendModel( -// ct, -// guid, -// new Dictionary { { "legend", val1 }, { "image", val2 }, { "size", val3 } }, -// false); -// -// Assert.AreEqual(val1, c.Legend); -// Assert.AreEqual(val3, c.Size); -// } -// -// [Test] -// public void First() -// { -// var publishedSnapshot = GetPublishedSnapshot(); -// var content = publishedSnapshot.Content.GetAtRoot().First(); -// Assert.AreEqual("Home", content.Name(VariationContextAccessor)); -// } -// -// [Test] -// public void Distinct() -// { -// var items = GetContent(1173) -// .Children(VariationContextAccessor) -// .Distinct() -// .Distinct() -// .ToIndexedArray(); -// -// Assert.AreEqual(5, items.Length); -// -// var item = items[0]; -// Assert.AreEqual(1174, item.Content.Id); -// Assert.IsTrue(item.IsFirst()); -// Assert.IsFalse(item.IsLast()); -// -// item = items[^1]; -// Assert.AreEqual(1176, item.Content.Id); -// Assert.IsFalse(item.IsFirst()); -// Assert.IsTrue(item.IsLast()); -// } -// -// [Test] -// public void OfType1() -// { -// var publishedSnapshot = GetPublishedSnapshot(); -// var items = publishedSnapshot.Content.GetAtRoot() -// .OfType() -// .Distinct() -// .ToIndexedArray(); -// Assert.AreEqual(1, items.Length); -// Assert.IsInstanceOf(items.First().Content); -// } -// -// [Test] -// public void OfType2() -// { -// var publishedSnapshot = GetPublishedSnapshot(); -// var content = publishedSnapshot.Content.GetAtRoot() -// .OfType() -// .Distinct() -// .ToIndexedArray(); -// Assert.AreEqual(1, content.Length); -// Assert.IsInstanceOf(content.First().Content); -// } -// -// [Test] -// public void OfType() -// { -// var content = GetContent(1173) -// .Children(VariationContextAccessor) -// .OfType() -// .First(x => x.UmbracoNaviHide); -// Assert.AreEqual(1176, content.Id); -// } -// -// [Test] -// public void Position() -// { -// var items = GetContent(1173).Children(VariationContextAccessor) -// .Where(x => x.Value(Mock.Of(), "umbracoNaviHide") == 0) -// .ToIndexedArray(); -// -// Assert.AreEqual(3, items.Length); -// -// Assert.IsTrue(items.First().IsFirst()); -// Assert.IsFalse(items.First().IsLast()); -// Assert.IsFalse(items.Skip(1).First().IsFirst()); -// Assert.IsFalse(items.Skip(1).First().IsLast()); -// Assert.IsFalse(items.Skip(2).First().IsFirst()); -// Assert.IsTrue(items.Skip(2).First().IsLast()); -// } -// -// private class ImageWithLegendModel : PublishedElement -// { -// public ImageWithLegendModel( -// IPublishedContentType contentType, -// Guid fragmentKey, -// Dictionary values, -// bool previewing) -// : base(contentType, fragmentKey, values, previewing) -// { -// } -// -// public string Legend => this.Value(Mock.Of(), "legend"); -// -// public IPublishedContent Image => this.Value(Mock.Of(), "image"); -// -// public int Size => this.Value(Mock.Of(), "size"); -// } -// -// // [PublishedModel("ContentType2")] -// // public class ContentType2 : PublishedContentModel -// // { -// // #region Plumbing -// -// // public ContentType2(IPublishedContent content, IPublishedValueFallback fallback) -// // : base(content, fallback) -// // { } -// -// // #endregion -// -// // public int Prop1 => this.Value(Mock.Of(), "prop1"); -// // } -// -// // [PublishedModel("ContentType2Sub")] -// // public class ContentType2Sub : ContentType2 -// // { -// // #region Plumbing -// -// // public ContentType2Sub(IPublishedContent content, IPublishedValueFallback fallback) -// // : base(content, fallback) -// // { } -// -// // #endregion -// // } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedMediaTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedMediaTests.cs deleted file mode 100644 index 979618144f57..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedMediaTests.cs +++ /dev/null @@ -1,242 +0,0 @@ -// using System.Collections.Generic; -// using System.Linq; -// using Moq; -// using NUnit.Framework; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Core.PropertyEditors; -// using Umbraco.Cms.Core.Strings; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Infrastructure.Serialization; -// using Umbraco.Cms.Tests.Common.Builders; -// using Umbraco.Cms.Tests.Common.Builders.Extensions; -// using Umbraco.Cms.Tests.UnitTests.TestHelpers; -// using Umbraco.Extensions; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache; -// -// FIXME: Reintroduce if relevant -// /// -// /// Tests the typed extension methods on IPublishedContent using the DefaultPublishedMediaStore -// /// -// [TestFixture] -// public class PublishedMediaTests : PublishedSnapshotServiceTestBase -// { -// [SetUp] -// public override void Setup() -// { -// base.Setup(); -// -// var dataTypes = GetDefaultDataTypes().ToList(); -// var serializer = new SystemTextConfigurationEditorJsonSerializer(); -// var rteDataType = new DataType(new VoidEditor("RTE", Mock.Of()), serializer) { Id = 4 }; -// dataTypes.Add(rteDataType); -// _dataTypes = dataTypes.ToArray(); -// -// _propertyDataTypes = new Dictionary -// { -// // defaults will just use the first one -// [string.Empty] = _dataTypes[0], -// -// // content uses the RTE -// ["content"] = _dataTypes[1], -// }; -// } -// -// private Dictionary _propertyDataTypes; -// private DataType[] _dataTypes; -// -// private ContentNodeKit CreateRoot(out MediaType mediaType) -// { -// mediaType = new MediaType(ShortStringHelper, -1); -// -// var item1Data = new ContentDataBuilder() -// .WithName("Content 1") -// .WithProperties(new PropertyDataBuilder() -// .WithPropertyData("content", "
This is some content
") -// .Build()) -// -// // build with a dynamically created media type -// .Build(ShortStringHelper, _propertyDataTypes, mediaType, "image2"); -// -// var item1 = ContentNodeKitBuilder.CreateWithContent( -// mediaType.Id, -// 1, -// "-1,1", -// draftData: item1Data, -// publishedData: item1Data); -// -// return item1; -// } -// -// private IEnumerable CreateChildren( -// int startId, -// ContentNodeKit parent, -// IMediaType mediaType, -// int count) -// { -// for (var i = 0; i < count; i++) -// { -// var id = startId + i + 1; -// -// var item1Data = new ContentDataBuilder() -// .WithName("Child " + id) -// .WithProperties(new PropertyDataBuilder() -// .WithPropertyData("content", "
This is some content
") -// .Build()) -// .Build(); -// -// var parentPath = parent.Node.Path; -// -// var item1 = ContentNodeKitBuilder.CreateWithContent( -// mediaType.Id, -// id, -// $"{parentPath},{id}", -// draftData: item1Data, -// publishedData: item1Data); -// -// yield return item1; -// } -// } -// -// private void InitializeWithHierarchy( -// out int rootId, -// out IReadOnlyList firstLevelChildren, -// out IReadOnlyList secondLevelChildren) -// { -// var cache = new List(); -// var root = CreateRoot(out var mediaType); -// firstLevelChildren = CreateChildren(10, root, mediaType, 3).ToList(); -// secondLevelChildren = CreateChildren(20, firstLevelChildren[0], mediaType, 3).ToList(); -// cache.Add(root); -// cache.AddRange(firstLevelChildren); -// cache.AddRange(secondLevelChildren); -// InitializedCache(null, null, _dataTypes, cache, new[] { mediaType }); -// rootId = root.Node.Id; -// } -// -// [Test] -// public void Get_Property_Value_Uses_Converter() -// { -// var cache = CreateRoot(out var mediaType); -// InitializedCache(null, null, _dataTypes.ToArray(), new[] { cache }, new[] { mediaType }); -// -// var publishedMedia = GetMedia(1); -// -// var propVal = publishedMedia.Value(PublishedValueFallback, "content"); -// Assert.IsInstanceOf(propVal); -// Assert.AreEqual("
This is some content
", propVal.ToString()); -// -// var propVal2 = publishedMedia.Value(PublishedValueFallback, "content"); -// Assert.IsInstanceOf(propVal2); -// Assert.AreEqual("
This is some content
", propVal2.ToString()); -// -// var propVal3 = publishedMedia.Value(PublishedValueFallback, "Content"); -// Assert.IsInstanceOf(propVal3); -// Assert.AreEqual("
This is some content
", propVal3.ToString()); -// } -// -// [Test] -// public void Children() -// { -// InitializeWithHierarchy( -// out var rootId, -// out var firstLevelChildren, -// out var secondLevelChildren); -// -// var publishedMedia = GetMedia(rootId); -// -// var rootChildren = publishedMedia.Children(VariationContextAccessor); -// Assert.IsTrue(rootChildren.Select(x => x.Id).ContainsAll(firstLevelChildren.Select(x => x.Node.Id))); -// -// var publishedChild1 = GetMedia(firstLevelChildren[0].Node.Id); -// var subChildren = publishedChild1.Children(VariationContextAccessor); -// Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(secondLevelChildren.Select(x => x.Node.Id))); -// } -// -// [Test] -// public void Descendants() -// { -// InitializeWithHierarchy( -// out var rootId, -// out var firstLevelChildren, -// out var secondLevelChildren); -// -// var publishedMedia = GetMedia(rootId); -// var rootDescendants = publishedMedia.Descendants(VariationContextAccessor); -// -// var descendentIds = -// firstLevelChildren.Select(x => x.Node.Id).Concat(secondLevelChildren.Select(x => x.Node.Id)); -// -// Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(descendentIds)); -// -// var publishedChild1 = GetMedia(firstLevelChildren[0].Node.Id); -// var subDescendants = publishedChild1.Descendants(VariationContextAccessor); -// Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(secondLevelChildren.Select(x => x.Node.Id))); -// } -// -// [Test] -// public void DescendantsOrSelf() -// { -// InitializeWithHierarchy( -// out var rootId, -// out var firstLevelChildren, -// out var secondLevelChildren); -// -// var publishedMedia = GetMedia(rootId); -// var rootDescendantsOrSelf = publishedMedia.DescendantsOrSelf(VariationContextAccessor); -// var descendentAndSelfIds = firstLevelChildren.Select(x => x.Node.Id) -// .Concat(secondLevelChildren.Select(x => x.Node.Id)) -// .Append(rootId); -// -// Assert.IsTrue(rootDescendantsOrSelf.Select(x => x.Id).ContainsAll(descendentAndSelfIds)); -// -// var publishedChild1 = GetMedia(firstLevelChildren[0].Node.Id); -// var subDescendantsOrSelf = publishedChild1.DescendantsOrSelf(VariationContextAccessor); -// Assert.IsTrue(subDescendantsOrSelf.Select(x => x.Id).ContainsAll( -// secondLevelChildren.Select(x => x.Node.Id).Append(firstLevelChildren[0].Node.Id))); -// } -// -// [Test] -// public void Parent() -// { -// InitializeWithHierarchy( -// out var rootId, -// out var firstLevelChildren, -// out var secondLevelChildren); -// -// var publishedMedia = GetMedia(rootId); -// Assert.AreEqual(null, publishedMedia.Parent); -// -// var publishedChild1 = GetMedia(firstLevelChildren[0].Node.Id); -// Assert.AreEqual(publishedMedia.Id, publishedChild1.Parent.Id); -// -// var publishedSubChild1 = GetMedia(secondLevelChildren[0].Node.Id); -// Assert.AreEqual(firstLevelChildren[0].Node.Id, publishedSubChild1.Parent.Id); -// } -// -// [Test] -// public void Ancestors() -// { -// InitializeWithHierarchy( -// out var rootId, -// out var firstLevelChildren, -// out var secondLevelChildren); -// -// var publishedSubChild1 = GetMedia(secondLevelChildren[0].Node.Id); -// Assert.IsTrue(publishedSubChild1.Ancestors().Select(x => x.Id) -// .ContainsAll(new[] { firstLevelChildren[0].Node.Id, rootId })); -// } -// -// [Test] -// public void AncestorsOrSelf() -// { -// InitializeWithHierarchy( -// out var rootId, -// out var firstLevelChildren, -// out var secondLevelChildren); -// -// var publishedSubChild1 = GetMedia(secondLevelChildren[0].Node.Id); -// Assert.IsTrue(publishedSubChild1.AncestorsOrSelf().Select(x => x.Id) -// .ContainsAll(new[] { secondLevelChildren[0].Node.Id, firstLevelChildren[0].Node.Id, rootId })); -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedSnapshotServiceCollectionTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedSnapshotServiceCollectionTests.cs deleted file mode 100644 index 9955338c2089..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedSnapshotServiceCollectionTests.cs +++ /dev/null @@ -1,1346 +0,0 @@ -// using NUnit.Framework; -// using Umbraco.Cms.Core.Cache; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Core.Models.PublishedContent; -// using Umbraco.Cms.Core.Services.Changes; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Infrastructure.PublishedCache.DataSource; -// using Umbraco.Cms.Tests.Common.Builders; -// using Umbraco.Cms.Tests.UnitTests.TestHelpers; -// using Umbraco.Extensions; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class PublishedSnapshotServiceCollectionTests : PublishedSnapshotServiceTestBase -// { -// [SetUp] -// public override void Setup() -// { -// base.Setup(); -// -// var propertyType = -// new PropertyType(TestHelper.ShortStringHelper, "Umbraco.Void.Editor", ValueStorageType.Nvarchar) -// { -// Alias = "prop", -// DataTypeId = 3, -// Variations = ContentVariation.Nothing, -// }; -// _contentTypeInvariant = -// new ContentType(TestHelper.ShortStringHelper, -1) -// { -// Id = 2, -// Alias = "itype", -// Variations = ContentVariation.Nothing, -// }; -// _contentTypeInvariant.AddPropertyType(propertyType); -// -// propertyType = -// new PropertyType(TestHelper.ShortStringHelper, "Umbraco.Void.Editor", ValueStorageType.Nvarchar) -// { -// Alias = "prop", -// DataTypeId = 3, -// Variations = ContentVariation.Culture, -// }; -// _contentTypeVariant = -// new ContentType(TestHelper.ShortStringHelper, -1) -// { -// Id = 3, -// Alias = "vtype", -// Variations = ContentVariation.Culture, -// }; -// _contentTypeVariant.AddPropertyType(propertyType); -// -// _contentTypes = new[] { _contentTypeInvariant, _contentTypeVariant }; -// } -// -// private ContentType _contentTypeInvariant; -// private ContentType _contentTypeVariant; -// private ContentType[] _contentTypes; -// -// private IEnumerable GetNestedVariantKits() -// { -// var paths = new Dictionary { { -1, "-1" } }; -// -// // 1x variant (root) -// yield return CreateVariantKit(1, -1, 1, paths); -// -// // 1x invariant under root -// yield return CreateInvariantKit(4, 1, 1, paths); -// -// // 1x variant under root -// yield return CreateVariantKit(7, 1, 4, paths); -// -// // 2x mixed under invariant -// yield return CreateVariantKit(10, 4, 1, paths); -// yield return CreateInvariantKit(11, 4, 2, paths); -// -// // 2x mixed under variant -// yield return CreateVariantKit(12, 7, 1, paths); -// yield return CreateInvariantKit(13, 7, 2, paths); -// } -// -// private IEnumerable GetInvariantKits() -// { -// var paths = new Dictionary { { -1, "-1" } }; -// -// yield return CreateInvariantKit(1, -1, 1, paths); -// yield return CreateInvariantKit(2, -1, 2, paths); -// yield return CreateInvariantKit(3, -1, 3, paths); -// -// yield return CreateInvariantKit(4, 1, 1, paths); -// yield return CreateInvariantKit(5, 1, 2, paths); -// yield return CreateInvariantKit(6, 1, 3, paths); -// -// yield return CreateInvariantKit(7, 2, 3, paths); -// yield return CreateInvariantKit(8, 2, 2, paths); -// yield return CreateInvariantKit(9, 2, 1, paths); -// -// yield return CreateInvariantKit(10, 3, 1, paths); -// -// yield return CreateInvariantKit(11, 4, 1, paths); -// yield return CreateInvariantKit(12, 4, 2, paths); -// } -// -// private ContentNodeKit CreateInvariantKit(int id, int parentId, int sortOrder, Dictionary paths) -// { -// if (!paths.TryGetValue(parentId, out var parentPath)) -// { -// throw new Exception("Unknown parent."); -// } -// -// var path = paths[id] = parentPath + "," + id; -// var level = path.Count(x => x == ','); -// var now = DateTime.Now; -// -// var contentData = ContentDataBuilder.CreateBasic("N" + id, now); -// -// return ContentNodeKitBuilder.CreateWithContent( -// _contentTypeInvariant.Id, -// id, -// path, -// sortOrder, -// level, -// parentId, -// 0, -// Guid.NewGuid(), -// DateTime.Now, -// null, -// contentData); -// } -// -// private IEnumerable GetVariantKits() -// { -// var paths = new Dictionary { { -1, "-1" } }; -// -// yield return CreateVariantKit(1, -1, 1, paths); -// yield return CreateVariantKit(2, -1, 2, paths); -// yield return CreateVariantKit(3, -1, 3, paths); -// -// yield return CreateVariantKit(4, 1, 1, paths); -// yield return CreateVariantKit(5, 1, 2, paths); -// yield return CreateVariantKit(6, 1, 3, paths); -// -// yield return CreateVariantKit(7, 2, 3, paths); -// yield return CreateVariantKit(8, 2, 2, paths); -// yield return CreateVariantKit(9, 2, 1, paths); -// -// yield return CreateVariantKit(10, 3, 1, paths); -// -// yield return CreateVariantKit(11, 4, 1, paths); -// yield return CreateVariantKit(12, 4, 2, paths); -// } -// -// private static Dictionary GetCultureInfos(int id, DateTime now) -// { -// var en = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; -// var fr = new[] { 1, 3, 4, 6, 7, 9, 10, 12 }; -// -// var infos = new Dictionary(); -// if (en.Contains(id)) -// { -// infos["en-US"] = new CultureVariation { Name = "N" + id + "-" + "en-US", Date = now, IsDraft = false }; -// } -// -// if (fr.Contains(id)) -// { -// infos["fr-FR"] = new CultureVariation { Name = "N" + id + "-" + "fr-FR", Date = now, IsDraft = false }; -// } -// -// return infos; -// } -// -// private ContentNodeKit CreateVariantKit(int id, int parentId, int sortOrder, Dictionary paths) -// { -// if (!paths.TryGetValue(parentId, out var parentPath)) -// { -// throw new Exception("Unknown parent."); -// } -// -// var path = paths[id] = parentPath + "," + id; -// var level = path.Count(x => x == ','); -// var now = DateTime.Now; -// -// var contentData = ContentDataBuilder.CreateVariant( -// "N" + id, -// GetCultureInfos(id, now), -// now); -// -// return ContentNodeKitBuilder.CreateWithContent( -// _contentTypeVariant.Id, -// id, -// path, -// sortOrder, -// level, -// parentId, -// draftData: null, -// publishedData: contentData); -// } -// -// private IEnumerable GetVariantWithDraftKits() -// { -// var paths = new Dictionary { { -1, "-1" } }; -// -// Dictionary GetCultureInfos(int id, DateTime now) -// { -// var en = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; -// var fr = new[] { 1, 3, 4, 6, 7, 9, 10, 12 }; -// -// var infos = new Dictionary(); -// if (en.Contains(id)) -// { -// infos["en-US"] = new CultureVariation { Name = "N" + id + "-" + "en-US", Date = now, IsDraft = false }; -// } -// -// if (fr.Contains(id)) -// { -// infos["fr-FR"] = new CultureVariation { Name = "N" + id + "-" + "fr-FR", Date = now, IsDraft = false }; -// } -// -// return infos; -// } -// -// ContentNodeKit CreateKit(int id, int parentId, int sortOrder) -// { -// if (!paths.TryGetValue(parentId, out var parentPath)) -// { -// throw new Exception("Unknown parent."); -// } -// -// var path = paths[id] = parentPath + "," + id; -// var level = path.Count(x => x == ','); -// var now = DateTime.Now; -// -// ContentData CreateContentData(bool published) -// { -// return ContentDataBuilder.CreateVariant( -// "N" + id, -// GetCultureInfos(id, now), -// now, -// published); -// } -// -// var withDraft = id % 2 == 0; -// var withPublished = !withDraft; -// -// return ContentNodeKitBuilder.CreateWithContent( -// _contentTypeVariant.Id, -// id, -// path, -// sortOrder, -// level, -// parentId, -// draftData: withDraft ? CreateContentData(false) : null, -// publishedData: withPublished ? CreateContentData(true) : null); -// } -// -// yield return CreateKit(1, -1, 1); -// yield return CreateKit(2, -1, 2); -// yield return CreateKit(3, -1, 3); -// -// yield return CreateKit(4, 1, 1); -// yield return CreateKit(5, 1, 2); -// yield return CreateKit(6, 1, 3); -// -// yield return CreateKit(7, 2, 3); -// yield return CreateKit(8, 2, 2); -// yield return CreateKit(9, 2, 1); -// -// yield return CreateKit(10, 3, 1); -// -// yield return CreateKit(11, 4, 1); -// yield return CreateKit(12, 4, 2); -// } -// -// [Test] -// public void EmptyTest() -// { -// InitializedCache(Array.Empty(), _contentTypes); -// -// var snapshot = GetPublishedSnapshot(); -// -// var documents = snapshot.Content.GetAtRoot().ToArray(); -// Assert.AreEqual(0, documents.Length); -// } -// -// [Test] -// public void ChildrenTest() -// { -// InitializedCache(GetInvariantKits(), _contentTypes); -// -// var snapshot = GetPublishedSnapshot(); -// -// var documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1", "N2", "N3"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N4", "N5", "N6"); -// -// documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N9", "N8", "N7"); -// -// documents = snapshot.Content.GetById(3).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N10"); -// -// documents = snapshot.Content.GetById(4).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N11", "N12"); -// -// documents = snapshot.Content.GetById(10).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents); -// } -// -// [Test] -// public void ParentTest() -// { -// InitializedCache(GetInvariantKits(), _contentTypes); -// -// var snapshot = GetPublishedSnapshot(); -// -// Assert.IsNull(snapshot.Content.GetById(1).Parent); -// Assert.IsNull(snapshot.Content.GetById(2).Parent); -// Assert.IsNull(snapshot.Content.GetById(3).Parent); -// -// Assert.AreEqual(1, snapshot.Content.GetById(4).Parent?.Id); -// Assert.AreEqual(1, snapshot.Content.GetById(5).Parent?.Id); -// Assert.AreEqual(1, snapshot.Content.GetById(6).Parent?.Id); -// -// Assert.AreEqual(2, snapshot.Content.GetById(7).Parent?.Id); -// Assert.AreEqual(2, snapshot.Content.GetById(8).Parent?.Id); -// Assert.AreEqual(2, snapshot.Content.GetById(9).Parent?.Id); -// -// Assert.AreEqual(3, snapshot.Content.GetById(10).Parent?.Id); -// -// Assert.AreEqual(4, snapshot.Content.GetById(11).Parent?.Id); -// Assert.AreEqual(4, snapshot.Content.GetById(12).Parent?.Id); -// } -// -// [Test] -// public void MoveToRootTest() -// { -// InitializedCache(GetInvariantKits(), _contentTypes); -// -// // get snapshot -// var snapshot = GetPublishedSnapshot(); -// -// // do some changes -// var kit = NuCacheContentService.ContentKits[10]; -// NuCacheContentService.ContentKits[10] = ContentNodeKitBuilder.CreateWithContent( -// _contentTypeInvariant.Id, -// kit.Node.Id, -// "-1,10", -// 4, -// 1, -// -1, -// draftData: null, -// publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name)); -// -// // notify -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 10, -// ChangeTypes = TreeChangeTypes.RefreshBranch -// } -// }, -// out _, -// out _); -// -// // changes that *I* make are immediately visible on the current snapshot -// var documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1", "N2", "N3", "N10"); -// -// documents = snapshot.Content.GetById(3).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents); -// -// Assert.IsNull(snapshot.Content.GetById(10).Parent); -// } -// -// [Test] -// public void MoveFromRootTest() -// { -// InitializedCache(GetInvariantKits(), _contentTypes); -// -// // get snapshot -// var snapshot = GetPublishedSnapshot(); -// -// // do some changes -// var kit = NuCacheContentService.ContentKits[1]; -// NuCacheContentService.ContentKits[1] = ContentNodeKitBuilder.CreateWithContent( -// _contentTypeInvariant.Id, -// kit.Node.Id, -// "-1,3,10,1", -// 1, -// 1, -// 10, -// draftData: null, -// publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name)); -// -// // notify -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 1, -// ChangeTypes = TreeChangeTypes.RefreshBranch -// } -// }, -// out _, -// out _); -// -// // changes that *I* make are immediately visible on the current snapshot -// var documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N2", "N3"); -// -// documents = snapshot.Content.GetById(10).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N1"); -// -// Assert.AreEqual(10, snapshot.Content.GetById(1).Parent?.Id); -// } -// -// [Test] -// public void ReOrderTest() -// { -// InitializedCache(GetInvariantKits(), _contentTypes); -// -// // get snapshot -// var snapshot = GetPublishedSnapshot(); -// -// // do some changes -// var kit = NuCacheContentService.ContentKits[7]; -// NuCacheContentService.ContentKits[7] = ContentNodeKitBuilder.CreateWithContent( -// _contentTypeInvariant.Id, -// kit.Node.Id, -// kit.Node.Path, -// 1, -// kit.Node.Level, -// kit.Node.ParentContentId, -// draftData: null, -// publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name)); -// -// kit = NuCacheContentService.ContentKits[8]; -// NuCacheContentService.ContentKits[8] = ContentNodeKitBuilder.CreateWithContent( -// _contentTypeInvariant.Id, -// kit.Node.Id, -// kit.Node.Path, -// 3, -// kit.Node.Level, -// kit.Node.ParentContentId, -// draftData: null, -// publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name)); -// -// kit = NuCacheContentService.ContentKits[9]; -// NuCacheContentService.ContentKits[9] = ContentNodeKitBuilder.CreateWithContent( -// _contentTypeInvariant.Id, -// kit.Node.Id, -// kit.Node.Path, -// 2, -// kit.Node.Level, -// kit.Node.ParentContentId, -// draftData: null, -// publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name)); -// -// // notify -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() -// { -// Id = kit.Node.ParentContentId, -// ChangeTypes = TreeChangeTypes.RefreshBranch -// } -// }, -// out _, -// out _); -// -// // changes that *I* make are immediately visible on the current snapshot -// var documents = snapshot.Content.GetById(kit.Node.ParentContentId).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N7", "N9", "N8"); -// } -// -// [Test] -// public void MoveTest() -// { -// InitializedCache(GetInvariantKits(), _contentTypes); -// -// // get snapshot -// var snapshot = GetPublishedSnapshot(); -// -// // do some changes -// var kit = NuCacheContentService.ContentKits[4]; -// NuCacheContentService.ContentKits[4] = ContentNodeKitBuilder.CreateWithContent( -// _contentTypeInvariant.Id, -// kit.Node.Id, -// kit.Node.Path, -// 2, -// kit.Node.Level, -// kit.Node.ParentContentId, -// draftData: null, -// publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name)); -// -// kit = NuCacheContentService.ContentKits[5]; -// NuCacheContentService.ContentKits[5] = ContentNodeKitBuilder.CreateWithContent( -// _contentTypeInvariant.Id, -// kit.Node.Id, -// kit.Node.Path, -// 3, -// kit.Node.Level, -// kit.Node.ParentContentId, -// draftData: null, -// publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name)); -// -// kit = NuCacheContentService.ContentKits[6]; -// NuCacheContentService.ContentKits[6] = ContentNodeKitBuilder.CreateWithContent( -// _contentTypeInvariant.Id, -// kit.Node.Id, -// kit.Node.Path, -// 4, -// kit.Node.Level, -// kit.Node.ParentContentId, -// draftData: null, -// publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name)); -// -// kit = NuCacheContentService.ContentKits[7]; -// NuCacheContentService.ContentKits[7] = ContentNodeKitBuilder.CreateWithContent( -// _contentTypeInvariant.Id, -// kit.Node.Id, -// "-1,1,7", -// 1, -// kit.Node.Level, -// 1, -// draftData: null, -// publishedData: ContentDataBuilder.CreateBasic(kit.PublishedData.Name)); -// -// // notify -// SnapshotService.Notify( -// new[] -// { -// // removal must come first -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 2, -// ChangeTypes = TreeChangeTypes.RefreshBranch -// }, -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 1, -// ChangeTypes = TreeChangeTypes.RefreshBranch -// } -// }, -// out _, -// out _); -// -// // changes that *I* make are immediately visible on the current snapshot -// var documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N7", "N4", "N5", "N6"); -// -// documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N9", "N8"); -// -// Assert.AreEqual(1, snapshot.Content.GetById(7).Parent?.Id); -// } -// -// [Test] -// public void Clear_Branch_Locked() -// { -// // This test replicates an issue we saw here https://github.com/umbraco/Umbraco-CMS/pull/7907#issuecomment-610259393 -// // The data was sent to me and this replicates it's structure -// var paths = new Dictionary { { -1, "-1" } }; -// -// InitializedCache( -// new List -// { -// CreateInvariantKit(1, -1, 1, paths), // first level -// CreateInvariantKit(2, 1, 1, paths), // second level -// CreateInvariantKit(3, 2, 1, paths), // third level -// -// CreateInvariantKit(4, 3, 1, paths), // fourth level (we'll copy this one to the same level) -// -// CreateInvariantKit(5, 4, 1, paths), // 6th level -// -// CreateInvariantKit(6, 5, 2, paths), // 7th level -// CreateInvariantKit(7, 5, 3, paths), -// CreateInvariantKit(8, 5, 4, paths), -// CreateInvariantKit(9, 5, 5, paths), -// CreateInvariantKit(10, 5, 6, paths), -// }, -// _contentTypes); -// -// // get snapshot -// var snapshot = GetPublishedSnapshot(); -// -// var snapshotService = (PublishedSnapshotService)SnapshotService; -// var contentStore = snapshotService.GetContentStore(); -// -// // This will set a flag to force creating a new Gen next time the store is locked (i.e. In Notify) -// contentStore.CreateSnapshot(); -// -// // notify - which ensures there are 2 generations in the cache meaning each LinkedNode has a Next value. -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 4, -// ChangeTypes = TreeChangeTypes.RefreshBranch -// } -// }, -// out _, -// out _); -// -// // refresh the branch again, this used to show the issue where a null ref exception would occur -// // because in the ClearBranchLocked logic, when SetValueLocked was called within a recursive call -// // to a child, we null out the .Value of the LinkedNode within the while loop because we didn't capture -// // this value before recursing. -// Assert.DoesNotThrow(() => -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 4, -// ChangeTypes = TreeChangeTypes.RefreshBranch -// } -// }, -// out _, -// out _)); -// } -// -// [Test] -// public void NestedVariationChildrenTest() -// { -// InitializedCache(GetNestedVariantKits(), _contentTypes); -// -// // get snapshot -// var snapshot = GetPublishedSnapshot(); -// -// // TEST with en-us variation context -// VariationContextAccessor.VariationContext = new VariationContext("en-US"); -// -// var documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1-en-US"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N4", "N7-en-US"); -// -// // Get the invariant and list children, there's a variation context so it should return invariant AND en-us variants -// documents = snapshot.Content.GetById(4).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N10-en-US", "N11"); -// -// // Get the variant and list children, there's a variation context so it should return invariant AND en-us variants -// documents = snapshot.Content.GetById(7).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N12-en-US", "N13"); -// -// // TEST with fr-fr variation context -// VariationContextAccessor.VariationContext = new VariationContext("fr-FR"); -// -// documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1-fr-FR"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N4", "N7-fr-FR"); -// -// // Get the invariant and list children, there's a variation context so it should return invariant AND en-us variants -// documents = snapshot.Content.GetById(4).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N10-fr-FR", "N11"); -// -// // Get the variant and list children, there's a variation context so it should return invariant AND en-us variants -// documents = snapshot.Content.GetById(7).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N12-fr-FR", "N13"); -// -// // TEST specific cultures -// documents = snapshot.Content.GetAtRoot("fr-FR").ToArray(); -// AssertDocuments(documents, "N1-fr-FR"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor, "fr-FR").ToArray(); -// AssertDocuments(documents, "N4", "N7-fr-FR"); // NOTE: Returns invariant, this is expected -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor, string.Empty).ToArray(); -// AssertDocuments(documents, "N4"); // Only returns invariant since that is what was requested -// -// documents = snapshot.Content.GetById(4).Children(VariationContextAccessor, "fr-FR").ToArray(); -// AssertDocuments(documents, "N10-fr-FR", "N11"); // NOTE: Returns invariant, this is expected -// documents = snapshot.Content.GetById(4).Children(VariationContextAccessor, string.Empty).ToArray(); -// AssertDocuments(documents, "N11"); // Only returns invariant since that is what was requested -// -// documents = snapshot.Content.GetById(7).Children(VariationContextAccessor, "fr-FR").ToArray(); -// AssertDocuments(documents, "N12-fr-FR", "N13"); // NOTE: Returns invariant, this is expected -// documents = snapshot.Content.GetById(7).Children(VariationContextAccessor, string.Empty).ToArray(); -// AssertDocuments(documents, "N13"); // Only returns invariant since that is what was requested -// -// // TEST without variation context -// // This will actually convert the culture to "" which will be invariant since that's all it will know how to do -// // This will return a NULL name for culture specific entities because there is no variation context -// VariationContextAccessor.VariationContext = null; -// -// documents = snapshot.Content.GetAtRoot().ToArray(); -// -// // will return nothing because there's only variant at root -// Assert.AreEqual(0, documents.Length); -// -// // so we'll continue to getting the known variant, do not fully assert this because the Name will NULL -// documents = snapshot.Content.GetAtRoot("fr-FR").ToArray(); -// Assert.AreEqual(1, documents.Length); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N4"); -// -// // Get the invariant and list children -// documents = snapshot.Content.GetById(4).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N11"); -// -// // Get the variant and list children -// documents = snapshot.Content.GetById(7).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N13"); -// } -// -// [Test] -// public void VariantChildrenTest() -// { -// InitializedCache(GetVariantKits(), _contentTypes); -// -// // get snapshot -// var snapshot = GetPublishedSnapshot(); -// -// VariationContextAccessor.VariationContext = new VariationContext("en-US"); -// -// var documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1-en-US", "N2-en-US", "N3-en-US"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N4-en-US", "N5-en-US", "N6-en-US"); -// -// documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N9-en-US", "N8-en-US", "N7-en-US"); -// -// documents = snapshot.Content.GetById(3).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N10-en-US"); -// -// documents = snapshot.Content.GetById(4).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N11-en-US", "N12-en-US"); -// -// documents = snapshot.Content.GetById(10).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents); -// -// VariationContextAccessor.VariationContext = new VariationContext("fr-FR"); -// -// documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1-fr-FR", "N3-fr-FR"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N4-fr-FR", "N6-fr-FR"); -// -// documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N9-fr-FR", "N7-fr-FR"); -// -// documents = snapshot.Content.GetById(3).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N10-fr-FR"); -// -// documents = snapshot.Content.GetById(4).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N12-fr-FR"); -// -// documents = snapshot.Content.GetById(10).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor, "*").ToArray(); -// AssertDocuments(documents, "N4-fr-FR", string.Empty, "N6-fr-FR"); -// AssertDocuments("en-US", documents, "N4-en-US", "N5-en-US", "N6-en-US"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor, "en-US").ToArray(); -// AssertDocuments(documents, "N4-fr-FR", string.Empty, "N6-fr-FR"); -// AssertDocuments("en-US", documents, "N4-en-US", "N5-en-US", "N6-en-US"); -// -// documents = snapshot.Content.GetById(1).ChildrenForAllCultures.ToArray(); -// AssertDocuments(documents, "N4-fr-FR", string.Empty, "N6-fr-FR"); -// AssertDocuments("en-US", documents, "N4-en-US", "N5-en-US", "N6-en-US"); -// -// documents = snapshot.Content.GetAtRoot("*").ToArray(); -// AssertDocuments(documents, "N1-fr-FR", string.Empty, "N3-fr-FR"); -// -// documents = snapshot.Content.GetById(1).DescendantsOrSelf(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N1-fr-FR", "N4-fr-FR", "N12-fr-FR", "N6-fr-FR"); -// -// documents = snapshot.Content.GetById(1).DescendantsOrSelf(VariationContextAccessor, "*").ToArray(); -// AssertDocuments(documents, "N1-fr-FR", "N4-fr-FR", string.Empty /*11*/, "N12-fr-FR", string.Empty /*5*/, "N6-fr-FR"); -// } -// -// [Test] -// public void RemoveTest() -// { -// InitializedCache(GetInvariantKits(), _contentTypes); -// -// // get snapshot -// var snapshot = GetPublishedSnapshot(); -// -// var documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1", "N2", "N3"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N4", "N5", "N6"); -// -// documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N9", "N8", "N7"); -// -// // notify -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() // remove last -// { -// Id = 3, -// ChangeTypes = TreeChangeTypes.Remove -// }, -// new ContentCacheRefresher.JsonPayload() // remove middle -// { -// Id = 5, -// ChangeTypes = TreeChangeTypes.Remove -// }, -// new ContentCacheRefresher.JsonPayload() // remove first -// { -// Id = 9, -// ChangeTypes = TreeChangeTypes.Remove -// } -// }, -// out _, -// out _); -// -// documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1", "N2"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N4", "N6"); -// -// documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N8", "N7"); -// -// // notify -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() // remove first -// { -// Id = 1, -// ChangeTypes = TreeChangeTypes.Remove -// }, -// new ContentCacheRefresher.JsonPayload() // remove -// { -// Id = 8, -// ChangeTypes = TreeChangeTypes.Remove -// }, -// new ContentCacheRefresher.JsonPayload() // remove -// { -// Id = 7, -// ChangeTypes = TreeChangeTypes.Remove -// } -// }, -// out _, -// out _); -// -// documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N2"); -// -// documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents); -// } -// -// [Test] -// public void UpdateTest() -// { -// InitializedCache(GetInvariantKits(), _contentTypes); -// -// // get snapshot -// var snapshot = GetPublishedSnapshot(); -// -// var snapshotService = (PublishedSnapshotService)SnapshotService; -// var contentStore = snapshotService.GetContentStore(); -// -// var parentNodes = contentStore.Test.GetValues(1); -// var parentNode = parentNodes[0]; -// AssertLinkedNode(parentNode.contentNode, -1, -1, 2, 4, 6); -// Assert.AreEqual(1, parentNode.gen); -// -// var documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1", "N2", "N3"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N4", "N5", "N6"); -// -// documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N9", "N8", "N7"); -// -// // notify -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 1, -// ChangeTypes = TreeChangeTypes.RefreshBranch -// }, -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 2, -// ChangeTypes = TreeChangeTypes.RefreshNode -// } -// }, -// out _, -// out _); -// -// parentNodes = contentStore.Test.GetValues(1); -// Assert.AreEqual(2, parentNodes.Length); -// parentNode = parentNodes[1]; // get the first gen -// AssertLinkedNode(parentNode.contentNode, -1, -1, 2, 4, 6); // the structure should have remained the same -// Assert.AreEqual(1, parentNode.gen); -// parentNode = parentNodes[0]; // get the latest gen -// AssertLinkedNode(parentNode.contentNode, -1, -1, 2, 4, 6); // the structure should have remained the same -// Assert.AreEqual(2, parentNode.gen); -// -// documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1", "N2", "N3"); -// -// documents = snapshot.Content.GetById(1).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N4", "N5", "N6"); -// -// documents = snapshot.Content.GetById(2).Children(VariationContextAccessor).ToArray(); -// AssertDocuments(documents, "N9", "N8", "N7"); -// } -// -// [Test] -// public void AtRootTest() -// { -// InitializedCache(GetVariantWithDraftKits(), _contentTypes); -// -// // get snapshot -// var snapshot = GetPublishedSnapshot(); -// -// VariationContextAccessor.VariationContext = new VariationContext("en-US"); -// -// // N2 is draft only -// var documents = snapshot.Content.GetAtRoot().ToArray(); -// AssertDocuments(documents, "N1-en-US", /*"N2-en-US",*/ "N3-en-US"); -// -// documents = snapshot.Content.GetAtRoot(true).ToArray(); -// AssertDocuments(documents, "N1-en-US", "N2-en-US", "N3-en-US"); -// } -// -// [Test] -// public void Set_All_Fast_Sorted_Ensure_LastChildContentId() -// { -// // see https://github.com/umbraco/Umbraco-CMS/issues/6353 -// IEnumerable GetKits() -// { -// var paths = new Dictionary { { -1, "-1" } }; -// -// yield return CreateInvariantKit(1, -1, 1, paths); -// yield return CreateInvariantKit(2, 1, 1, paths); -// } -// -// InitializedCache(GetKits(), _contentTypes); -// -// var snapshotService = (PublishedSnapshotService)SnapshotService; -// var contentStore = snapshotService.GetContentStore(); -// -// var parentNodes = contentStore.Test.GetValues(1); -// var parentNode = parentNodes[0]; -// AssertLinkedNode(parentNode.contentNode, -1, -1, -1, 2, 2); -// -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 2, -// ChangeTypes = TreeChangeTypes.Remove -// } -// }, -// out _, -// out _); -// -// parentNodes = contentStore.Test.GetValues(1); -// parentNode = parentNodes[0]; -// -// AssertLinkedNode(parentNode.contentNode, -1, -1, -1, -1, -1); -// } -// -// [Test] -// public void Remove_Node_Ensures_Linked_List() -// { -// // NOTE: these tests are not using real scopes, in which case a Scope does not control -// // how the snapshots generations work. We are forcing new snapshot generations manually. -// IEnumerable GetKits() -// { -// var paths = new Dictionary { { -1, "-1" } }; -// -// // root -// yield return CreateInvariantKit(1, -1, 1, paths); -// -// // children -// yield return CreateInvariantKit(2, 1, 1, paths); -// yield return CreateInvariantKit(3, 1, 2, paths); // middle child -// yield return CreateInvariantKit(4, 1, 3, paths); -// } -// -// InitializedCache(GetKits(), _contentTypes); -// -// var snapshotService = (PublishedSnapshotService)SnapshotService; -// var contentStore = snapshotService.GetContentStore(); -// -// Assert.AreEqual(1, contentStore.Test.LiveGen); -// Assert.IsTrue(contentStore.Test.NextGen); -// -// var parentNode = contentStore.Test.GetValues(1)[0]; -// Assert.AreEqual(1, parentNode.gen); -// AssertLinkedNode(parentNode.contentNode, -1, -1, -1, 2, 4); -// -// var child1 = contentStore.Test.GetValues(2)[0]; -// Assert.AreEqual(1, child1.gen); -// AssertLinkedNode(child1.contentNode, 1, -1, 3, -1, -1); -// -// var child2 = contentStore.Test.GetValues(3)[0]; -// Assert.AreEqual(1, child2.gen); -// AssertLinkedNode(child2.contentNode, 1, 2, 4, -1, -1); -// -// var child3 = contentStore.Test.GetValues(4)[0]; -// Assert.AreEqual(1, child3.gen); -// AssertLinkedNode(child3.contentNode, 1, 3, -1, -1, -1); -// -// // This will set a flag to force creating a new Gen next time the store is locked (i.e. In Notify) -// contentStore.CreateSnapshot(); -// -// Assert.IsFalse(contentStore.Test.NextGen); -// -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() // remove middle child -// { -// Id = 3, -// ChangeTypes = TreeChangeTypes.Remove -// } -// }, -// out _, -// out _); -// -// Assert.AreEqual(2, contentStore.Test.LiveGen); -// Assert.IsTrue(contentStore.Test.NextGen); -// -// var parentNodes = contentStore.Test.GetValues(1); -// Assert.AreEqual(1, parentNodes.Length); // the parent doesn't get changed, not new gen's are added -// parentNode = parentNodes[0]; -// Assert.AreEqual(1, parentNode.gen); // the parent node's gen has not changed -// AssertLinkedNode(parentNode.contentNode, -1, -1, -1, 2, 4); -// -// child1 = contentStore.Test.GetValues(2)[0]; -// Assert.AreEqual(2, child1.gen); // there is now 2x gen's of this item -// AssertLinkedNode(child1.contentNode, 1, -1, 4, -1, -1); -// -// child2 = contentStore.Test.GetValues(3)[0]; -// Assert.AreEqual(2, child2.gen); // there is now 2x gen's of this item -// Assert.IsNull(child2.contentNode); // because it doesn't exist anymore -// -// child3 = contentStore.Test.GetValues(4)[0]; -// Assert.AreEqual(2, child3.gen); // there is now 2x gen's of this item -// AssertLinkedNode(child3.contentNode, 1, 2, -1, -1, -1); -// } -// -// [Test] -// public void Refresh_Node_Ensures_Linked_list() -// { -// // NOTE: these tests are not using real scopes, in which case a Scope does not control -// // how the snapshots generations work. We are forcing new snapshot generations manually. -// IEnumerable GetKits() -// { -// var paths = new Dictionary { { -1, "-1" } }; -// -// // root -// yield return CreateInvariantKit(100, -1, 1, paths); -// -// // site -// yield return CreateInvariantKit(2, 100, 1, paths); -// yield return CreateInvariantKit(1, 100, 2, paths); // middle child -// yield return CreateInvariantKit(3, 100, 3, paths); -// -// // children of 1 -// yield return CreateInvariantKit(20, 1, 1, paths); -// yield return CreateInvariantKit(30, 1, 2, paths); -// yield return CreateInvariantKit(40, 1, 3, paths); -// } -// -// InitializedCache(GetKits(), _contentTypes); -// -// var snapshotService = (PublishedSnapshotService)SnapshotService; -// var contentStore = snapshotService.GetContentStore(); -// -// Assert.AreEqual(1, contentStore.Test.LiveGen); -// Assert.IsTrue(contentStore.Test.NextGen); -// -// var middleNode = contentStore.Test.GetValues(1)[0]; -// Assert.AreEqual(1, middleNode.gen); -// AssertLinkedNode(middleNode.contentNode, 100, 2, 3, 20, 40); -// -// // This will set a flag to force creating a new Gen next time the store is locked (i.e. In Notify) -// contentStore.CreateSnapshot(); -// -// Assert.IsFalse(contentStore.Test.NextGen); -// -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 1, -// ChangeTypes = TreeChangeTypes.RefreshNode -// } -// }, -// out _, -// out _); -// -// Assert.AreEqual(2, contentStore.Test.LiveGen); -// Assert.IsTrue(contentStore.Test.NextGen); -// -// middleNode = contentStore.Test.GetValues(1)[0]; -// Assert.AreEqual(2, middleNode.gen); -// AssertLinkedNode(middleNode.contentNode, 100, 2, 3, 20, 40); -// } -// -// /// -// /// This addresses issue: https://github.com/umbraco/Umbraco-CMS/issues/6698 -// /// -// /// -// /// This test mimics if someone were to: -// /// 1) Unpublish a "middle child" -// /// 2) Save and publish it -// /// 3) Publish it with descendants -// /// 4) Repeat steps 2 and 3 -// /// Which has caused an exception. To replicate this test: -// /// 1) RefreshBranch with kits for a branch where the top most node is unpublished -// /// 2) RefreshBranch with kits for the branch where the top most node is published -// /// 3) RefreshBranch with kits for the branch where the top most node is published -// /// 4) RefreshNode -// /// 5) RefreshBranch with kits for the branch where the top most node is published -// /// -// [Test] -// public void Refresh_Branch_With_Alternating_Publish_Flags() -// { -// // NOTE: these tests are not using real scopes, in which case a Scope does not control -// // how the snapshots generations work. We are forcing new snapshot generations manually. -// IEnumerable GetKits() -// { -// var paths = new Dictionary { { -1, "-1" } }; -// -// // root -// yield return CreateInvariantKit(100, -1, 1, paths); -// -// // site -// yield return CreateInvariantKit(2, 100, 1, paths); -// yield return CreateInvariantKit(1, 100, 2, paths); // middle child -// yield return CreateInvariantKit(3, 100, 3, paths); -// -// // children of 1 -// yield return CreateInvariantKit(20, 1, 1, paths); -// yield return CreateInvariantKit(30, 1, 2, paths); -// yield return CreateInvariantKit(40, 1, 3, paths); -// } -// -// // init with all published -// InitializedCache(GetKits(), _contentTypes); -// -// var snapshotService = (PublishedSnapshotService)SnapshotService; -// var contentStore = snapshotService.GetContentStore(); -// -// var rootKit = NuCacheContentService.ContentKits[1].Clone(PublishedModelFactory); -// -// void ChangePublishFlagOfRoot(bool published, int assertGen, TreeChangeTypes changeType) -// { -// // This will set a flag to force creating a new Gen next time the store is locked (i.e. In Notify) -// contentStore.CreateSnapshot(); -// -// Assert.IsFalse(contentStore.Test.NextGen); -// -// // Change the root publish flag -// var kit = rootKit.Clone( -// PublishedModelFactory, -// published ? null : rootKit.PublishedData, -// published ? rootKit.PublishedData : null); -// NuCacheContentService.ContentKits[1] = kit; -// -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() -// { -// Id = 1, -// ChangeTypes = changeType -// } -// }, -// out _, -// out _); -// -// Assert.AreEqual(assertGen, contentStore.Test.LiveGen); -// Assert.IsTrue(contentStore.Test.NextGen); -// -// // get the latest gen for content Id 1 -// var (gen, contentNode) = contentStore.Test.GetValues(1)[0]; -// Assert.AreEqual(assertGen, gen); -// -// // even when unpublishing/re-publishing/etc... the linked list is always maintained -// AssertLinkedNode(contentNode, 100, 2, 3, 20, 40); -// } -// -// // unpublish the root -// ChangePublishFlagOfRoot(false, 2, TreeChangeTypes.RefreshBranch); -// -// // publish the root (since it's not published, it will cause a RefreshBranch) -// ChangePublishFlagOfRoot(true, 3, TreeChangeTypes.RefreshBranch); -// -// // publish root + descendants -// ChangePublishFlagOfRoot(true, 4, TreeChangeTypes.RefreshBranch); -// -// // save/publish the root (since it's already published, it will just cause a RefreshNode -// ChangePublishFlagOfRoot(true, 5, TreeChangeTypes.RefreshNode); -// -// // publish root + descendants -// ChangePublishFlagOfRoot(true, 6, TreeChangeTypes.RefreshBranch); -// } -// -// [Test] -// public void Refresh_Branch_Ensures_Linked_List() -// { -// // NOTE: these tests are not using real scopes, in which case a Scope does not control -// // how the snapshots generations work. We are forcing new snapshot generations manually. -// IEnumerable GetKits() -// { -// var paths = new Dictionary { { -1, "-1" } }; -// -// // root -// yield return CreateInvariantKit(1, -1, 1, paths); -// -// // children -// yield return CreateInvariantKit(2, 1, 1, paths); -// yield return CreateInvariantKit(3, 1, 2, paths); // middle child -// yield return CreateInvariantKit(4, 1, 3, paths); -// } -// -// InitializedCache(GetKits(), _contentTypes); -// -// var snapshotService = (PublishedSnapshotService)SnapshotService; -// var contentStore = snapshotService.GetContentStore(); -// -// Assert.AreEqual(1, contentStore.Test.LiveGen); -// Assert.IsTrue(contentStore.Test.NextGen); -// -// var parentNode = contentStore.Test.GetValues(1)[0]; -// Assert.AreEqual(1, parentNode.gen); -// AssertLinkedNode(parentNode.contentNode, -1, -1, -1, 2, 4); -// -// var child1 = contentStore.Test.GetValues(2)[0]; -// Assert.AreEqual(1, child1.gen); -// AssertLinkedNode(child1.contentNode, 1, -1, 3, -1, -1); -// -// var child2 = contentStore.Test.GetValues(3)[0]; -// Assert.AreEqual(1, child2.gen); -// AssertLinkedNode(child2.contentNode, 1, 2, 4, -1, -1); -// -// var child3 = contentStore.Test.GetValues(4)[0]; -// Assert.AreEqual(1, child3.gen); -// AssertLinkedNode(child3.contentNode, 1, 3, -1, -1, -1); -// -// // This will set a flag to force creating a new Gen next time the store is locked (i.e. In Notify) -// contentStore.CreateSnapshot(); -// -// Assert.IsFalse(contentStore.Test.NextGen); -// -// SnapshotService.Notify( -// new[] -// { -// new ContentCacheRefresher.JsonPayload() // remove middle child -// { -// Id = 3, -// ChangeTypes = TreeChangeTypes.RefreshBranch -// } -// }, -// out _, -// out _); -// -// Assert.AreEqual(2, contentStore.Test.LiveGen); -// Assert.IsTrue(contentStore.Test.NextGen); -// -// var parentNodes = contentStore.Test.GetValues(1); -// Assert.AreEqual(1, parentNodes.Length); // the parent doesn't get changed, not new gen's are added -// parentNode = parentNodes[0]; -// Assert.AreEqual(1, parentNode.gen); // the parent node's gen has not changed -// AssertLinkedNode(parentNode.contentNode, -1, -1, -1, 2, 4); -// -// child1 = contentStore.Test.GetValues(2)[0]; -// Assert.AreEqual(2, child1.gen); // there is now 2x gen's of this item -// AssertLinkedNode(child1.contentNode, 1, -1, 3, -1, -1); -// -// child2 = contentStore.Test.GetValues(3)[0]; -// Assert.AreEqual(2, child2.gen); // there is now 2x gen's of this item -// AssertLinkedNode(child2.contentNode, 1, 2, 4, -1, -1); -// -// child3 = contentStore.Test.GetValues(4)[0]; -// Assert.AreEqual(2, child3.gen); // there is now 2x gen's of this item -// AssertLinkedNode(child3.contentNode, 1, 3, -1, -1, -1); -// } -// -// [Test] -// public void MultipleCacheIteration() -// { -// // see https://github.com/umbraco/Umbraco-CMS/issues/7798 -// InitializedCache(GetInvariantKits(), _contentTypes); -// var snapshot = GetPublishedSnapshot(); -// -// var items = snapshot.Content.GetAtRoot().Where(x => x.ContentType.Alias == "itype").ToArray(); -// Assert.AreEqual(items.Length, items.Length); -// } -// -// private void AssertLinkedNode(ContentNode node, int parent, int prevSibling, int nextSibling, int firstChild, int lastChild) -// { -// Assert.AreEqual(parent, node.ParentContentId); -// Assert.AreEqual(prevSibling, node.PreviousSiblingContentId); -// Assert.AreEqual(nextSibling, node.NextSiblingContentId); -// Assert.AreEqual(firstChild, node.FirstChildContentId); -// Assert.AreEqual(lastChild, node.LastChildContentId); -// } -// -// private void AssertDocuments(IPublishedContent[] documents, params string[] names) -// { -// Assert.AreEqual(names.Length, documents.Length); -// for (var i = 0; i < names.Length; i++) -// { -// Assert.AreEqual(names[i], documents[i].Name); -// } -// } -// -// private void AssertDocuments(string culture, IPublishedContent[] documents, params string[] names) -// { -// Assert.AreEqual(names.Length, documents.Length); -// for (var i = 0; i < names.Length; i++) -// { -// Assert.AreEqual(names[i], documents[i].Name(VariationContextAccessor, culture)); -// } -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedSnapshotServiceContentTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedSnapshotServiceContentTests.cs deleted file mode 100644 index e80ac3929dc6..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/PublishedSnapshotServiceContentTests.cs +++ /dev/null @@ -1,207 +0,0 @@ -// using System.Collections.Generic; -// using Moq; -// using NUnit.Framework; -// using Umbraco.Cms.Core.Cache; -// using Umbraco.Cms.Core.Models; -// using Umbraco.Cms.Core.Models.PublishedContent; -// using Umbraco.Cms.Core.Services.Changes; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Infrastructure.PublishedCache.DataSource; -// using Umbraco.Cms.Tests.Common.Builders; -// using Umbraco.Cms.Tests.Common.Builders.Extensions; -// using Umbraco.Cms.Tests.UnitTests.TestHelpers; -// using Umbraco.Extensions; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class PublishedSnapshotServiceContentTests : PublishedSnapshotServiceTestBase -// { -// [SetUp] -// public override void Setup() -// { -// base.Setup(); -// -// _propertyType = -// new PropertyType(TestHelper.ShortStringHelper, "Umbraco.Void.Editor", ValueStorageType.Nvarchar) -// { -// Alias = "prop", -// DataTypeId = 3, -// Variations = ContentVariation.Culture, -// }; -// _contentType = -// new ContentType(TestHelper.ShortStringHelper, -1) -// { -// Id = 2, -// Alias = "alias-ct", -// Variations = ContentVariation.Culture, -// }; -// _contentType.AddPropertyType(_propertyType); -// -// var contentTypes = new[] { _contentType }; -// -// InitializedCache(new[] { CreateKit() }, contentTypes); -// } -// -// private ContentType _contentType; -// private PropertyType _propertyType; -// -// private ContentNodeKit CreateKit() -// { -// var draftData = new ContentDataBuilder() -// .WithName("It Works2!") -// .WithPublished(false) -// .WithProperties(new Dictionary -// { -// ["prop"] = new[] -// { -// new PropertyData { Culture = string.Empty, Segment = string.Empty, Value = "val2" }, -// new PropertyData { Culture = "fr-FR", Segment = string.Empty, Value = "val-fr2" }, -// new PropertyData { Culture = "en-UK", Segment = string.Empty, Value = "val-uk2" }, -// new PropertyData { Culture = "dk-DA", Segment = string.Empty, Value = "val-da2" }, -// new PropertyData { Culture = "de-DE", Segment = string.Empty, Value = "val-de2" }, -// }, -// }) -// .WithCultureInfos(new Dictionary -// { -// // draft data = everything, and IsDraft indicates what's edited -// ["fr-FR"] = new() { Name = "name-fr2", IsDraft = true, Date = new DateTime(2018, 01, 03, 01, 00, 00) }, -// ["en-UK"] = new() { Name = "name-uk2", IsDraft = true, Date = new DateTime(2018, 01, 04, 01, 00, 00) }, -// ["dk-DA"] = new() { Name = "name-da2", IsDraft = true, Date = new DateTime(2018, 01, 05, 01, 00, 00) }, -// ["de-DE"] = new() { Name = "name-de1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00) }, -// }) -// .Build(); -// -// var publishedData = new ContentDataBuilder() -// .WithName("It Works1!") -// .WithPublished(true) -// .WithProperties(new Dictionary -// { -// ["prop"] = new[] -// { -// new PropertyData { Culture = string.Empty, Segment = string.Empty, Value = "val1" }, -// new PropertyData { Culture = "fr-FR", Segment = string.Empty, Value = "val-fr1" }, -// new PropertyData { Culture = "en-UK", Segment = string.Empty, Value = "val-uk1" }, -// }, -// }) -// .WithCultureInfos(new Dictionary -// { -// // published data = only what's actually published, and IsDraft has to be false -// ["fr-FR"] = new() { Name = "name-fr1", IsDraft = false, Date = new DateTime(2018, 01, 01, 01, 00, 00) }, -// ["en-UK"] = new() { Name = "name-uk1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00) }, -// ["de-DE"] = new() { Name = "name-de1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00) }, -// }) -// .Build(); -// -// var kit = ContentNodeKitBuilder.CreateWithContent( -// 2, -// 1, -// "-1,1", -// 0, -// draftData: draftData, -// publishedData: publishedData); -// -// return kit; -// } -// -// [Test] -// public void Verifies_Variant_Data() -// { -// // this test implements a full standalone NuCache (based upon a test IDataSource, does not -// // use any local db files, does not rely on any database) - and tests variations -// -// // get a snapshot, get a published content -// var snapshot = GetPublishedSnapshot(); -// var publishedContent = snapshot.Content.GetById(1); -// -// Assert.IsNotNull(publishedContent); -// Assert.AreEqual("val1", publishedContent.Value(Mock.Of(), "prop")); -// Assert.AreEqual("val-fr1", publishedContent.Value(Mock.Of(), "prop", "fr-FR")); -// Assert.AreEqual("val-uk1", publishedContent.Value(Mock.Of(), "prop", "en-UK")); -// -// Assert.AreEqual(publishedContent.Name(VariationContextAccessor), string.Empty); // no invariant name for varying content -// Assert.AreEqual("name-fr1", publishedContent.Name(VariationContextAccessor, "fr-FR")); -// Assert.AreEqual("name-uk1", publishedContent.Name(VariationContextAccessor, "en-UK")); -// -// var draftContent = snapshot.Content.GetById(true, 1); -// Assert.AreEqual("val2", draftContent.Value(Mock.Of(), "prop")); -// Assert.AreEqual("val-fr2", draftContent.Value(Mock.Of(), "prop", "fr-FR")); -// Assert.AreEqual("val-uk2", draftContent.Value(Mock.Of(), "prop", "en-UK")); -// -// Assert.AreEqual(draftContent.Name(VariationContextAccessor), string.Empty); // no invariant name for varying content -// Assert.AreEqual("name-fr2", draftContent.Name(VariationContextAccessor, "fr-FR")); -// Assert.AreEqual("name-uk2", draftContent.Name(VariationContextAccessor, "en-UK")); -// -// // now french is default -// VariationContextAccessor.VariationContext = new VariationContext("fr-FR"); -// Assert.AreEqual("val-fr1", publishedContent.Value(Mock.Of(), "prop")); -// Assert.AreEqual("name-fr1", publishedContent.Name(VariationContextAccessor)); -// Assert.AreEqual(new DateTime(2018, 01, 01, 01, 00, 00), publishedContent.CultureDate(VariationContextAccessor)); -// -// // now uk is default -// VariationContextAccessor.VariationContext = new VariationContext("en-UK"); -// Assert.AreEqual("val-uk1", publishedContent.Value(Mock.Of(), "prop")); -// Assert.AreEqual("name-uk1", publishedContent.Name(VariationContextAccessor)); -// Assert.AreEqual(new DateTime(2018, 01, 02, 01, 00, 00), publishedContent.CultureDate(VariationContextAccessor)); -// -// // invariant needs to be retrieved explicitly, when it's not default -// Assert.AreEqual("val1", publishedContent.Value(Mock.Of(), "prop", string.Empty)); -// -// // but, -// // if the content type / property type does not vary, then it's all invariant again -// // modify the content type and property type, notify the snapshot service -// _contentType.Variations = ContentVariation.Nothing; -// _propertyType.Variations = ContentVariation.Nothing; -// SnapshotService.Notify(new[] -// { -// new ContentTypeCacheRefresher.JsonPayload("IContentType", publishedContent.ContentType.Id, ContentTypeChangeTypes.RefreshMain), -// }); -// -// // get a new snapshot (nothing changed in the old one), get the published content again -// var anotherSnapshot = SnapshotService.CreatePublishedSnapshot(null); -// var againContent = anotherSnapshot.Content.GetById(1); -// -// Assert.AreEqual(ContentVariation.Nothing, againContent.ContentType.Variations); -// Assert.AreEqual(ContentVariation.Nothing, againContent.ContentType.GetPropertyType("prop").Variations); -// -// // now, "no culture" means "invariant" -// Assert.AreEqual("It Works1!", againContent.Name(VariationContextAccessor)); -// Assert.AreEqual("val1", againContent.Value(Mock.Of(), "prop")); -// } -// -// [Test] -// public void Verifies_Published_And_Draft_Content() -// { -// // get the published published content -// var snapshot = GetPublishedSnapshot(); -// var c1 = snapshot.Content.GetById(1); -// -// // published content = nothing is draft here -// Assert.IsFalse(c1.IsDraft("fr-FR")); -// Assert.IsFalse(c1.IsDraft("en-UK")); -// Assert.IsFalse(c1.IsDraft("dk-DA")); -// Assert.IsFalse(c1.IsDraft("de-DE")); -// -// // and only those with published name, are published -// Assert.IsTrue(c1.IsPublished("fr-FR")); -// Assert.IsTrue(c1.IsPublished("en-UK")); -// Assert.IsFalse(c1.IsDraft("dk-DA")); -// Assert.IsTrue(c1.IsPublished("de-DE")); -// -// // get the draft published content -// var c2 = snapshot.Content.GetById(true, 1); -// -// // draft content = we have drafts -// Assert.IsTrue(c2.IsDraft("fr-FR")); -// Assert.IsTrue(c2.IsDraft("en-UK")); -// Assert.IsTrue(c2.IsDraft("dk-DA")); -// Assert.IsFalse(c2.IsDraft("de-DE")); // except for the one that does not -// -// // and only those with published name, are published -// Assert.IsTrue(c2.IsPublished("fr-FR")); -// Assert.IsTrue(c2.IsPublished("en-UK")); -// Assert.IsFalse(c2.IsPublished("dk-DA")); -// Assert.IsTrue(c2.IsPublished("de-DE")); -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/RootNodeTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/RootNodeTests.cs deleted file mode 100644 index dc0baa6b18e6..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/RootNodeTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -// using System.Collections.Generic; -// using System.Linq; -// using NUnit.Framework; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Tests.Common.Published; -// using Umbraco.Cms.Tests.UnitTests.TestHelpers; -// -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache; -// -// FIXME: Reintroduce if relevant -// [TestFixture] -// public class RootNodeTests : PublishedSnapshotServiceTestBase -// { -// [SetUp] -// public override void Setup() -// { -// base.Setup(); -// -// var xml = PublishedContentXml.TestWithDatabaseXml(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// } -// -// [Test] -// public void PublishedContentHasNoRootNode() -// { -// var snapshot = GetPublishedSnapshot(); -// -// // there is no content node with ID -1 -// var content = snapshot.Content.GetById(-1); -// Assert.IsNull(content); -// -// // content at root has null parent -// content = snapshot.Content.GetById(1046); -// Assert.IsNotNull(content); -// Assert.AreEqual(1, content.Level); -// Assert.IsNull(content.Parent); -// -// // non-existing content is null -// content = snapshot.Content.GetById(666); -// Assert.IsNull(content); -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/UrlRoutesTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/UrlRoutesTests.cs deleted file mode 100644 index e0bb426b4f05..000000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/PublishedCache/UrlRoutesTests.cs +++ /dev/null @@ -1,366 +0,0 @@ -// using System.Collections.Generic; -// using System.Linq; -// using NUnit.Framework; -// using Umbraco.Cms.Infrastructure.PublishedCache; -// using Umbraco.Cms.Tests.Common.Published; -// using Umbraco.Cms.Tests.UnitTests.TestHelpers; -// -// FIXME: Reintroduce if relevant -// namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache; -// -// // purpose: test the values returned by PublishedContentCache.GetRouteById -// // and .GetByRoute (no caching at all, just routing nice URLs) including all -// // the quirks due to hideTopLevelFromPath and backward compatibility. -// public class UrlRoutesTests : PublishedSnapshotServiceTestBase -// { -// private static string GetXmlContent(int templateId) -// => @" -// -// -// ]> -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// "; -// -// /* -// * Just so it's documented somewhere, as of jan. 2017, routes obey the following pseudo-code: -// -// GetByRoute(route, hide = null): -// -// route is "[id]/[path]" -// -// hide = hide ?? global.hide -// -// root = id ? node(id) : document -// -// content = cached(route) ?? DetermineIdByRoute(route, hide) -// -// # route is "1234/path/to/content", finds "content" -// # but if there is domain 5678 on "to", the *true* route of "content" is "5678/content" -// # so although the route does match, we don't cache it -// # there are not other reason not to cache it -// -// if content and no domain between root and content: -// cache route (as trusted) -// -// return content -// -// -// DetermineIdByRoute(route, hide): -// -// route is "[id]/[path]" -// -// try return NavigateRoute(id ?? 0, path, hide:hide) -// return null -// -// -// NavigateRoute(id, path, hide): -// -// if path: -// if id: -// start = node(id) -// else: -// start = document -// -// # 'navigate ... from ...' uses lowest sortOrder in case of collision -// -// if hide and ![id]: -// # if hiding, then for "/foo" we want to look for "/[any]/foo" -// for each child of start: -// try return navigate path from child -// -// # but if it fails, we also want to try "/foo" -// # fail now if more than one part eg "/foo/bar" -// if path is "/[any]/...": -// fail -// -// try return navigate path from start -// -// else: -// if id: -// return node(id) -// else: -// return root node with lowest sortOrder -// -// -// GetRouteById(id): -// -// -// route = cached(id) -// if route: -// return route -// -// # never cache the route, it may be colliding -// -// route = DetermineRouteById(id) -// if route: -// cache route (as not trusted) -// -// return route -// -// -// -// DetermineRouteById(id): -// -// -// node = node(id) -// -// walk up from node to domain or root, assemble parts = URL segments -// -// if !domain and global.hide: -// if id.parent: -// # got /top/[path]content, can remove /top -// remove top part -// else: -// # got /content, should remove only if it is the -// # node with lowest sort order -// root = root node with lowest sortOrder -// if root == node: -// remove top part -// -// compose path from parts -// route = assemble "[domain.id]/[path]" -// return route -// -// */ -// -// /* -// * The Xml structure for the following tests is: -// * -// * root -// * A 1000 -// * B 1001 -// * C 1002 -// * D 1003 -// * X 2000 -// * Y 2001 -// * Z 2002 -// * A 2003 -// * B 2004 -// * C 2005 -// * E 2006 -// * -// */ -// -// [TestCase(1000, false, "/a")] -// [TestCase(1001, false, "/a/b")] -// [TestCase(1002, false, "/a/b/c")] -// [TestCase(1003, false, "/a/b/c/d")] -// [TestCase(2000, false, "/x")] -// [TestCase(2001, false, "/x/y")] -// [TestCase(2002, false, "/x/y/z")] -// [TestCase(2003, false, "/x/a")] -// [TestCase(2004, false, "/x/b")] -// [TestCase(2005, false, "/x/b/c")] -// [TestCase(2006, false, "/x/b/e")] -// public void GetRouteByIdNoHide(int id, bool hide, string expected) -// { -// GlobalSettings.HideTopLevelNodeFromPath = hide; -// -// var xml = GetXmlContent(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// var cache = GetPublishedSnapshot().Content; -// -// var route = cache.GetRouteById(false, id); -// Assert.AreEqual(expected, route); -// } -// -// [TestCase(1000, true, "/")] -// [TestCase(1001, true, "/b")] -// [TestCase(1002, true, "/b/c")] -// [TestCase(1003, true, "/b/c/d")] -// [TestCase(2000, true, "/x")] -// [TestCase(2001, true, "/y")] -// [TestCase(2002, true, "/y/z")] -// [TestCase(2003, true, "/a")] -// [TestCase(2004, true, "/b")] // collision! -// [TestCase(2005, true, "/b/c")] // collision! -// [TestCase(2006, true, "/b/e")] // risky! -// public void GetRouteByIdHide(int id, bool hide, string expected) -// { -// GlobalSettings.HideTopLevelNodeFromPath = hide; -// -// var xml = GetXmlContent(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// var cache = GetPublishedSnapshot().Content; -// -// var route = cache.GetRouteById(false, id); -// Assert.AreEqual(expected, route); -// } -// -// [Test] -// public void GetRouteByIdCache() -// { -// GlobalSettings.HideTopLevelNodeFromPath = false; -// -// var xml = GetXmlContent(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// var cache = GetPublishedSnapshot().Content; -// -// var route = cache.GetRouteById(false, 1000); -// Assert.AreEqual("/a", route); -// } -// -// [TestCase("/", false, 1000)] -// [TestCase("/a", false, 1000)] // yes! -// [TestCase("/a/b", false, 1001)] -// [TestCase("/a/b/c", false, 1002)] -// [TestCase("/a/b/c/d", false, 1003)] -// [TestCase("/x", false, 2000)] -// public void GetByRouteNoHide(string route, bool hide, int expected) -// { -// GlobalSettings.HideTopLevelNodeFromPath = hide; -// -// var xml = GetXmlContent(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// var cache = GetPublishedSnapshot().Content; -// -// const bool preview = false; // make sure we don't cache - but HOW? should be some sort of switch?! -// var content = cache.GetByRoute(preview, route); -// if (expected < 0) -// { -// Assert.IsNull(content); -// } -// else -// { -// Assert.IsNotNull(content); -// Assert.AreEqual(expected, content.Id); -// } -// } -// -// [TestCase("/", true, 1000)] -// [TestCase("/a", true, 2003)] -// [TestCase("/a/b", true, -1)] -// [TestCase("/x", true, 2000)] // oops! -// [TestCase("/x/y", true, -1)] // yes! -// [TestCase("/y", true, 2001)] -// [TestCase("/y/z", true, 2002)] -// [TestCase("/b", true, 1001)] // (hence the 2004 collision) -// [TestCase("/b/c", true, 1002)] // (hence the 2005 collision) -// public void GetByRouteHide(string route, bool hide, int expected) -// { -// GlobalSettings.HideTopLevelNodeFromPath = hide; -// -// var xml = GetXmlContent(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// var cache = GetPublishedSnapshot().Content; -// -// const bool preview = false; // make sure we don't cache - but HOW? should be some sort of switch?! -// var content = cache.GetByRoute(preview, route); -// if (expected < 0) -// { -// Assert.IsNull(content); -// } -// else -// { -// Assert.IsNotNull(content); -// Assert.AreEqual(expected, content.Id); -// } -// } -// -// [Test] -// public void GetByRouteCache() -// { -// GlobalSettings.HideTopLevelNodeFromPath = false; -// -// var xml = GetXmlContent(1234); -// -// IEnumerable kits = PublishedContentXmlAdapter.GetContentNodeKits( -// xml, -// TestHelper.ShortStringHelper, -// out var contentTypes, -// out var dataTypes).ToList(); -// -// InitializedCache(kits, contentTypes, dataTypes); -// -// var cache = GetPublishedSnapshot().Content; -// -// var content = cache.GetByRoute(false, "/a/b/c"); -// Assert.IsNotNull(content); -// Assert.AreEqual(1002, content.Id); -// } -// } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Security/MemberUserStoreTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Security/MemberUserStoreTests.cs index 1976f925b0fb..cdea9af249a1 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Security/MemberUserStoreTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Security/MemberUserStoreTests.cs @@ -149,8 +149,8 @@ public async Task GivenIUpdateAUser_ThenIShouldGetASuccessResultAsync() Email = "fakeemail@umbraco.com", UserName = "fakeUsername", Comments = "hello", - LastLoginDateUtc = DateTime.UtcNow, - LastPasswordChangeDateUtc = DateTime.UtcNow, + LastLoginDate = DateTime.UtcNow, + LastPasswordChangeDate = DateTime.UtcNow, EmailConfirmed = true, AccessFailedCount = 3, LockoutEnd = DateTime.UtcNow.AddDays(10), @@ -192,8 +192,8 @@ public async Task GivenIUpdateAUser_ThenIShouldGetASuccessResultAsync() Assert.AreEqual(fakeUser.Email, mockMember.Email); Assert.AreEqual(fakeUser.UserName, mockMember.Username); Assert.AreEqual(fakeUser.Comments, mockMember.Comments); - Assert.AreEqual(fakeUser.LastPasswordChangeDateUtc.Value.ToLocalTime(), mockMember.LastPasswordChangeDate); - Assert.AreEqual(fakeUser.LastLoginDateUtc.Value.ToLocalTime(), mockMember.LastLoginDate); + Assert.AreEqual(fakeUser.LastPasswordChangeDate, mockMember.LastPasswordChangeDate); + Assert.AreEqual(fakeUser.LastLoginDate, mockMember.LastLoginDate); Assert.AreEqual(fakeUser.AccessFailedCount, mockMember.FailedPasswordAttempts); Assert.AreEqual(fakeUser.IsLockedOut, mockMember.IsLockedOut); Assert.AreEqual(fakeUser.IsApproved, mockMember.IsApproved); @@ -218,7 +218,7 @@ public async Task GivenIUpdateAUsersLoginPropertiesOnly_ThenIShouldGetASuccessRe Email = "a@b.com", UserName = "c", Comments = "e", - LastLoginDateUtc = DateTime.UtcNow, + LastLoginDate = DateTime.UtcNow, SecurityStamp = "abc", }; @@ -252,8 +252,8 @@ public async Task GivenIUpdateAUsersLoginPropertiesOnly_ThenIShouldGetASuccessRe Assert.AreEqual(fakeUser.Email, mockMember.Email); Assert.AreEqual(fakeUser.UserName, mockMember.Username); Assert.AreEqual(fakeUser.Comments, mockMember.Comments); - Assert.IsFalse(fakeUser.LastPasswordChangeDateUtc.HasValue); - Assert.AreEqual(fakeUser.LastLoginDateUtc.Value.ToLocalTime(), mockMember.LastLoginDate); + Assert.IsFalse(fakeUser.LastPasswordChangeDate.HasValue); + Assert.AreEqual(fakeUser.LastLoginDate.Value, mockMember.LastLoginDate); Assert.AreEqual(fakeUser.AccessFailedCount, mockMember.FailedPasswordAttempts); Assert.AreEqual(fakeUser.IsLockedOut, mockMember.IsLockedOut); Assert.AreEqual(fakeUser.IsApproved, mockMember.IsApproved); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ContentTypeBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ContentTypeBuilderTests.cs index eceebc2c88cd..ad83b29661f2 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ContentTypeBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ContentTypeBuilderTests.cs @@ -23,8 +23,8 @@ public void Is_Built_Correctly() const string testPropertyGroupName = "Content"; const int testParentId = 98; const int testCreatorId = 22; - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; const int testLevel = 3; const string testPath = "-1, 4, 10"; const int testSortOrder = 5; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilderTests.cs index 8cdcac7dc800..91fd5a08d856 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/DocumentEntitySlimBuilderTests.cs @@ -27,8 +27,8 @@ public void Is_Built_Correctly() const string testContentTypeIcon = "icon"; const string testContentTypeThumbnail = "thumb"; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; var builder = new DocumentEntitySlimBuilder(); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MediaTypeBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MediaTypeBuilderTests.cs index 4a02c8c9c01a..0c71433947f7 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MediaTypeBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MediaTypeBuilderTests.cs @@ -24,8 +24,8 @@ public void Is_Built_Correctly() const string testPropertyGroupName = "Additional Content"; const int testParentId = 98; const int testCreatorId = 22; - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; const int testLevel = 3; const string testPath = "-1, 4, 10"; const int testSortOrder = 5; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberBuilderTests.cs index fa9e770f7625..9025ae3fd056 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberBuilderTests.cs @@ -32,12 +32,12 @@ public void Is_Built_Correctly() const int testSortOrder = 5; const bool testTrashed = false; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; const int testFailedPasswordAttempts = 22; - var testLastLockoutDate = DateTime.Now.AddHours(-2); - var testLastLoginDate = DateTime.Now.AddHours(-3); - var testLastPasswordChangeDate = DateTime.Now.AddHours(-4); + var testLastLockoutDate = DateTime.UtcNow.AddHours(-2); + var testLastLoginDate = DateTime.UtcNow.AddHours(-3); + var testLastPasswordChangeDate = DateTime.UtcNow.AddHours(-4); var testPropertyType1 = new PropertyTypeDetail { Alias = "title", Name = "Title", SortOrder = 1, DataTypeId = -88 }; var testPropertyType2 = diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberGroupBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberGroupBuilderTests.cs index d612038daedf..f25e55df7689 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberGroupBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberGroupBuilderTests.cs @@ -18,8 +18,8 @@ public void Is_Built_Correctly() const string testName = "Test Group"; const int testCreatorId = 4; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; var builder = new MemberGroupBuilder(); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberTypeBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberTypeBuilderTests.cs index 6ec33489bdc3..31b52a983fb4 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberTypeBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MemberTypeBuilderTests.cs @@ -25,8 +25,8 @@ public void Is_Built_Correctly() const string testPropertyGroupName = "Content"; const int testParentId = 98; const int testCreatorId = 22; - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; const int testLevel = 3; const string testPath = "-1, 4, 10"; const int testSortOrder = 5; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyBuilderTests.cs index 4884fe371a01..5f04c3f9c051 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyBuilderTests.cs @@ -16,8 +16,8 @@ public void Is_Built_Correctly() // Arrange const int testId = 4; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; var testPropertyTypeId = 3; var builder = new PropertyBuilder(); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyGroupBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyGroupBuilderTests.cs index 8c0327e1692a..3d2819bf61a0 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyGroupBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyGroupBuilderTests.cs @@ -18,8 +18,8 @@ public void Is_Built_Correctly() var testKey = Guid.NewGuid(); const string testName = "Group1"; const int testSortOrder = 555; - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; const int testPropertyTypeId = 3; var builder = new PropertyGroupBuilder(); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeBuilderTests.cs index 3b4c41bce441..e6bee2276385 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/PropertyTypeBuilderTests.cs @@ -23,8 +23,8 @@ public void Is_Built_Correctly() const string testName = "Test"; const int testSortOrder = 9; const int testDataTypeId = 5; - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; const string testDescription = "testing"; const int testPropertyGroupId = 11; const bool testMandatory = true; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationBuilderTests.cs index 8b073bfe2397..a23a70e7425c 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationBuilderTests.cs @@ -19,8 +19,8 @@ public void Is_Built_Correctly() const int childId = 8; const int id = 4; var key = Guid.NewGuid(); - var createDate = DateTime.Now.AddHours(-1); - var updateDate = DateTime.Now; + var createDate = DateTime.UtcNow.AddHours(-1); + var updateDate = DateTime.UtcNow; const string comment = "test comment"; const int relationTypeId = 66; const string relationTypeAlias = "test"; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationTypeBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationTypeBuilderTests.cs index d176251a1e0b..fe04e930b24b 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationTypeBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RelationTypeBuilderTests.cs @@ -18,9 +18,9 @@ public void Is_Built_Correctly() const string alias = "test"; const string name = "Test"; var key = Guid.NewGuid(); - var createDate = DateTime.Now.AddHours(-2); - var updateDate = DateTime.Now.AddHours(-1); - var deleteDate = DateTime.Now; + var createDate = DateTime.UtcNow.AddHours(-2); + var updateDate = DateTime.UtcNow.AddHours(-1); + var deleteDate = DateTime.UtcNow; var parentObjectType = Guid.NewGuid(); var childObjectType = Guid.NewGuid(); const bool isBidirectional = true; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateBuilderTests.cs index 29551ee06b7d..c955bd5e407b 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/TemplateBuilderTests.cs @@ -19,8 +19,8 @@ public void Is_Built_Correctly() const string testAlias = "test"; const string testName = "Test"; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; const string testPath = "-1,3"; const string testContent = "blah"; const string testMasterTemplateAlias = "master"; diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserBuilderTests.cs index 52938dd53fb4..ab2dd3aea2ad 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserBuilderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/UserBuilderTests.cs @@ -22,12 +22,12 @@ public void Is_Built_Correctly() const bool testIsApproved = true; const bool testIsLockedOut = true; var testKey = Guid.NewGuid(); - var testCreateDate = DateTime.Now.AddHours(-1); - var testUpdateDate = DateTime.Now; + var testCreateDate = DateTime.UtcNow.AddHours(-1); + var testUpdateDate = DateTime.UtcNow; const int testFailedPasswordAttempts = 22; - var testLastLockoutDate = DateTime.Now.AddHours(-2); - var testLastLoginDate = DateTime.Now.AddHours(-3); - var testLastPasswordChangeDate = DateTime.Now.AddHours(-4); + var testLastLockoutDate = DateTime.UtcNow.AddHours(-2); + var testLastLoginDate = DateTime.UtcNow.AddHours(-3); + var testLastPasswordChangeDate = DateTime.UtcNow.AddHours(-4); var testComments = "comments"; var testSessionTimeout = 5; var testStartContentIds = new[] { 3 };