diff --git a/src/Umbraco.Cms.Api.Management/Controllers/Package/Created/UpdateCreatedPackageController.cs b/src/Umbraco.Cms.Api.Management/Controllers/Package/Created/UpdateCreatedPackageController.cs index 41bb904e4c..fb40488eb6 100644 --- a/src/Umbraco.Cms.Api.Management/Controllers/Package/Created/UpdateCreatedPackageController.cs +++ b/src/Umbraco.Cms.Api.Management/Controllers/Package/Created/UpdateCreatedPackageController.cs @@ -47,7 +47,6 @@ public class UpdateCreatedPackageController : CreatedPackageControllerBase return CreatedPackageNotFound(); } - // Macros are not included! PackageDefinition packageDefinition = _umbracoMapper.Map(updatePackageRequestModel, package); Attempt result = await _packagingService.UpdateCreatedPackageAsync(packageDefinition, CurrentUserKey(_backOfficeSecurityAccessor)); diff --git a/src/Umbraco.Cms.Api.Management/Factories/PackagePresentationFactory.cs b/src/Umbraco.Cms.Api.Management/Factories/PackagePresentationFactory.cs index 9adc39e610..5b4423d0d6 100644 --- a/src/Umbraco.Cms.Api.Management/Factories/PackagePresentationFactory.cs +++ b/src/Umbraco.Cms.Api.Management/Factories/PackagePresentationFactory.cs @@ -26,7 +26,6 @@ internal class PackagePresentationFactory : IPackagePresentationFactory public PackageDefinition CreatePackageDefinition(CreatePackageRequestModel createPackageRequestModel) { - // Macros are not included! PackageDefinition packageDefinition = _umbracoMapper.Map(createPackageRequestModel)!; // Temp Id, PackageId and PackagePath for the newly created package diff --git a/src/Umbraco.Cms.Api.Management/Mapping/Package/PackageViewModelMapDefinition.cs b/src/Umbraco.Cms.Api.Management/Mapping/Package/PackageViewModelMapDefinition.cs index 18e0d4c87f..4ab05a910d 100644 --- a/src/Umbraco.Cms.Api.Management/Mapping/Package/PackageViewModelMapDefinition.cs +++ b/src/Umbraco.Cms.Api.Management/Mapping/Package/PackageViewModelMapDefinition.cs @@ -17,7 +17,7 @@ public class PackageViewModelMapDefinition : IMapDefinition (_, _) => new PackageMigrationStatusResponseModel { PackageName = string.Empty }, Map); } - // Umbraco.Code.MapAll -Id -PackageId -PackagePath -Macros + // Umbraco.Code.MapAll -Id -PackageId -PackagePath private static void Map(PackageModelBase source, PackageDefinition target, MapperContext context) { target.Name = source.Name; diff --git a/src/Umbraco.Core/Cache/CacheKeys.cs b/src/Umbraco.Core/Cache/CacheKeys.cs index 04ae44a647..4ba8edf445 100644 --- a/src/Umbraco.Core/Cache/CacheKeys.cs +++ b/src/Umbraco.Core/Cache/CacheKeys.cs @@ -10,9 +10,6 @@ public static class CacheKeys // TODO: this one can probably be removed public const string TemplateFrontEndCacheKey = "template"; - public const string MacroContentCacheKey = "macroContent_"; // used in MacroRenderers - public const string MacroFromAliasCacheKey = "macroFromAlias_"; - public const string UserGroupGetByAliasCacheKeyPrefix = "UserGroupRepository_GetByAlias_"; public const string UserAllContentStartNodesPrefix = "AllContentStartNodes"; diff --git a/src/Umbraco.Core/Cache/DistributedCacheExtensions.cs b/src/Umbraco.Core/Cache/DistributedCacheExtensions.cs index 438c66a2c1..e02bee857b 100644 --- a/src/Umbraco.Core/Cache/DistributedCacheExtensions.cs +++ b/src/Umbraco.Core/Cache/DistributedCacheExtensions.cs @@ -212,24 +212,6 @@ public static class DistributedCacheExtensions #endregion - #region MacroCacheRefresher - - [Obsolete("Use the overload accepting IEnumerable instead. This overload will be removed in Umbraco 13.")] - public static void RefreshMacroCache(this DistributedCache dc, IMacro macro) - => dc.RefreshMacroCache(macro.Yield()); - - public static void RefreshMacroCache(this DistributedCache dc, IEnumerable macros) - => dc.RefreshByPayload(MacroCacheRefresher.UniqueId, macros.DistinctBy(x => (x.Id, x.Alias)).Select(x => new MacroCacheRefresher.JsonPayload(x.Id, x.Alias))); - - [Obsolete("Use the overload accepting IEnumerable instead. This overload will be removed in Umbraco 13.")] - public static void RemoveMacroCache(this DistributedCache dc, IMacro macro) - => dc.RemoveMacroCache(macro.Yield()); - - public static void RemoveMacroCache(this DistributedCache dc, IEnumerable macros) - => dc.RefreshByPayload(MacroCacheRefresher.UniqueId, macros.DistinctBy(x => (x.Id, x.Alias)).Select(x => new MacroCacheRefresher.JsonPayload(x.Id, x.Alias))); - - #endregion - #region ContentTypeCacheRefresher [Obsolete("Use the overload accepting IEnumerable instead to avoid allocating arrays. This overload will be removed in Umbraco 13.")] diff --git a/src/Umbraco.Core/Cache/NotificationHandlers/Implement/MacroDeletedDistributedCacheNotificationHandler.cs b/src/Umbraco.Core/Cache/NotificationHandlers/Implement/MacroDeletedDistributedCacheNotificationHandler.cs deleted file mode 100644 index 358f24ac18..0000000000 --- a/src/Umbraco.Core/Cache/NotificationHandlers/Implement/MacroDeletedDistributedCacheNotificationHandler.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Notifications; -using Umbraco.Extensions; - -namespace Umbraco.Cms.Core.Cache; - -/// -public sealed class MacroDeletedDistributedCacheNotificationHandler : DeletedDistributedCacheNotificationHandlerBase -{ - private readonly DistributedCache _distributedCache; - - /// - /// Initializes a new instance of the class. - /// - /// The distributed cache. - public MacroDeletedDistributedCacheNotificationHandler(DistributedCache distributedCache) - => _distributedCache = distributedCache; - - /// - protected override void Handle(IEnumerable entities) - => _distributedCache.RemoveMacroCache(entities); -} diff --git a/src/Umbraco.Core/Cache/NotificationHandlers/Implement/MacroSavedDistributedCacheNotificationHandler.cs b/src/Umbraco.Core/Cache/NotificationHandlers/Implement/MacroSavedDistributedCacheNotificationHandler.cs deleted file mode 100644 index 268d2786e6..0000000000 --- a/src/Umbraco.Core/Cache/NotificationHandlers/Implement/MacroSavedDistributedCacheNotificationHandler.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Notifications; -using Umbraco.Extensions; - -namespace Umbraco.Cms.Core.Cache; - -/// -public sealed class MacroSavedDistributedCacheNotificationHandler : SavedDistributedCacheNotificationHandlerBase -{ - private readonly DistributedCache _distributedCache; - - /// - /// Initializes a new instance of the class. - /// - /// The distributed cache. - public MacroSavedDistributedCacheNotificationHandler(DistributedCache distributedCache) - => _distributedCache = distributedCache; - - /// - protected override void Handle(IEnumerable entities) - => _distributedCache.RefreshMacroCache(entities); -} diff --git a/src/Umbraco.Core/Cache/Refreshers/Implement/MacroCacheRefresher.cs b/src/Umbraco.Core/Cache/Refreshers/Implement/MacroCacheRefresher.cs deleted file mode 100644 index 9975abae8c..0000000000 --- a/src/Umbraco.Core/Cache/Refreshers/Implement/MacroCacheRefresher.cs +++ /dev/null @@ -1,108 +0,0 @@ -using Umbraco.Cms.Core.Events; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Notifications; -using Umbraco.Cms.Core.Persistence.Repositories; -using Umbraco.Cms.Core.Serialization; - -namespace Umbraco.Cms.Core.Cache; - -public sealed class MacroCacheRefresher : PayloadCacheRefresherBase -{ - public MacroCacheRefresher( - AppCaches appCaches, - IJsonSerializer jsonSerializer, - IEventAggregator eventAggregator, - ICacheRefresherNotificationFactory factory) - : base(appCaches, jsonSerializer, eventAggregator, factory) - { - } - - #region Json - - public class JsonPayload - { - public JsonPayload(int id, string alias) - { - Id = id; - Alias = alias; - } - - public int Id { get; } - - public string Alias { get; } - } - - #endregion - - #region Define - - public static readonly Guid UniqueId = Guid.Parse("7B1E683C-5F34-43dd-803D-9699EA1E98CA"); - - public override Guid RefresherUniqueId => UniqueId; - - public override string Name => "Macro Cache Refresher"; - - #endregion - - #region Refresher - - public override void RefreshAll() - { - foreach (var prefix in GetAllMacroCacheKeys()) - { - AppCaches.RuntimeCache.ClearByKey(prefix); - } - - ClearAllIsolatedCacheByEntityType(); - - base.RefreshAll(); - } - - public override void Refresh(string json) - { - JsonPayload[]? payloads = Deserialize(json); - - if (payloads is not null) - { - Refresh(payloads); - } - } - - public override void Refresh(JsonPayload[] payloads) - { - foreach (JsonPayload payload in payloads) - { - foreach (var alias in GetCacheKeysForAlias(payload.Alias)) - { - AppCaches.RuntimeCache.ClearByKey(alias); - } - - Attempt macroRepoCache = AppCaches.IsolatedCaches.Get(); - if (macroRepoCache) - { - macroRepoCache.Result?.Clear(RepositoryCacheKeys.GetKey(payload.Id)); - macroRepoCache.Result?.Clear( - RepositoryCacheKeys - .GetKey(payload.Alias)); // Repository caching of macro definition by alias - } - } - - base.Refresh(payloads); - } - - #endregion - - #region Helpers - - internal static string[] GetAllMacroCacheKeys() => - new[] - { - CacheKeys.MacroContentCacheKey, // macro render cache - CacheKeys.MacroFromAliasCacheKey, // lookup macro by alias - }; - - internal static string[] GetCacheKeysForAlias(string alias) => - GetAllMacroCacheKeys().Select(x => x + alias).ToArray(); - - #endregion -} diff --git a/src/Umbraco.Core/Configuration/Models/ContentSettings.cs b/src/Umbraco.Core/Configuration/Models/ContentSettings.cs index 1c2caeb9bc..5bbbea3d8b 100644 --- a/src/Umbraco.Core/Configuration/Models/ContentSettings.cs +++ b/src/Umbraco.Core/Configuration/Models/ContentSettings.cs @@ -2,7 +2,6 @@ // See LICENSE for more details. using System.ComponentModel; -using Umbraco.Cms.Core.Macros; namespace Umbraco.Cms.Core.Configuration.Models; @@ -149,7 +148,6 @@ public class ContentSettings "; - internal const string StaticMacroErrors = "Inline"; internal const string StaticDisallowedUploadFiles = "ashx,aspx,ascx,config,cshtml,vbhtml,asmx,air,axd,xamlx"; internal const bool StaticShowDeprecatedPropertyEditors = false; internal const string StaticLoginBackgroundImage = "login/login.jpg"; @@ -188,12 +186,6 @@ public class ContentSettings [DefaultValue(StaticDefaultPreviewBadge)] public string PreviewBadge { get; set; } = StaticDefaultPreviewBadge; - /// - /// Gets or sets a value for the macro error behaviour. - /// - [DefaultValue(StaticMacroErrors)] - public MacroErrorBehaviour MacroErrors { get; set; } = Enum.Parse(StaticMacroErrors); - /// /// Gets or sets a value for the collection of file extensions that are disallowed for upload. /// diff --git a/src/Umbraco.Core/Configuration/Models/RichTextEditorSettings.cs b/src/Umbraco.Core/Configuration/Models/RichTextEditorSettings.cs index e48e90c0e6..77827fb009 100644 --- a/src/Umbraco.Core/Configuration/Models/RichTextEditorSettings.cs +++ b/src/Umbraco.Core/Configuration/Models/RichTextEditorSettings.cs @@ -86,7 +86,6 @@ public class RichTextEditorSettings { Alias = "umbblockpicker", Name = "Block", Mode = RichTextEditorCommandMode.All, }, - new RichTextEditorCommand { Alias = "umbmacro", Name = "Macro", Mode = RichTextEditorCommandMode.All }, new RichTextEditorCommand { Alias = "table", Name = "Table", Mode = RichTextEditorCommandMode.Insert }, new RichTextEditorCommand { diff --git a/src/Umbraco.Core/Constants-Applications.cs b/src/Umbraco.Core/Constants-Applications.cs index aa1f19c791..4a53ff455f 100644 --- a/src/Umbraco.Core/Constants-Applications.cs +++ b/src/Umbraco.Core/Constants-Applications.cs @@ -73,11 +73,6 @@ public static partial class Constants /// public const string Media = "media"; - /// - /// alias for the macro tree. - /// - public const string Macros = "macros"; - /// /// alias for the datatype tree. /// @@ -143,8 +138,6 @@ public static partial class Constants public const string PartialViews = "partialViews"; - public const string PartialViewMacros = "partialViewMacros"; - public const string LogViewer = "logViewer"; public const string Webhooks = "webhooks"; diff --git a/src/Umbraco.Core/Constants-Configuration.cs b/src/Umbraco.Core/Constants-Configuration.cs index 62703dfc6a..6d14f5c7c9 100644 --- a/src/Umbraco.Core/Constants-Configuration.cs +++ b/src/Umbraco.Core/Constants-Configuration.cs @@ -22,7 +22,6 @@ public static partial class Constants public const string ConfigModelsBuilderPrefix = ConfigPrefix + "ModelsBuilder:"; public const string ConfigSecurityPrefix = ConfigPrefix + "Security:"; public const string ConfigContentNotificationsEmail = ConfigContentNotificationsPrefix + "Email"; - public const string ConfigContentMacroErrors = ConfigContentPrefix + "MacroErrors"; public const string ConfigGlobalUseHttps = ConfigGlobalPrefix + "UseHttps"; public const string ConfigHostingDebug = ConfigHostingPrefix + "Debug"; public const string ConfigCustomErrorsMode = ConfigCustomErrorsPrefix + "Mode"; diff --git a/src/Umbraco.Core/Constants-HealthChecks.cs b/src/Umbraco.Core/Constants-HealthChecks.cs index 4bf250e4d6..256efbcc54 100644 --- a/src/Umbraco.Core/Constants-HealthChecks.cs +++ b/src/Umbraco.Core/Constants-HealthChecks.cs @@ -26,8 +26,6 @@ public static partial class Constants public static class Configuration { - public const string MacroErrorsCheck = "https://umbra.co/healthchecks-macro-errors"; - public const string TrySkipIisCustomErrorsCheck = "https://umbra.co/healthchecks-skip-iis-custom-errors"; diff --git a/src/Umbraco.Core/Constants-Icons.cs b/src/Umbraco.Core/Constants-Icons.cs index a18ff387e7..53501a012c 100644 --- a/src/Umbraco.Core/Constants-Icons.cs +++ b/src/Umbraco.Core/Constants-Icons.cs @@ -54,11 +54,6 @@ public static partial class Constants /// public const string ListView = "icon-thumbnail-list"; - /// - /// System macro icon. - /// - public const string Macro = "icon-settings-alt"; - /// /// System media file icon. /// diff --git a/src/Umbraco.Core/Constants-SystemDirectories.cs b/src/Umbraco.Core/Constants-SystemDirectories.cs index e6f9fae9fb..0db7ae4937 100644 --- a/src/Umbraco.Core/Constants-SystemDirectories.cs +++ b/src/Umbraco.Core/Constants-SystemDirectories.cs @@ -51,8 +51,6 @@ public static partial class Constants public const string PartialViews = MvcViews + "/Partials/"; - public const string MacroPartials = MvcViews + "/MacroPartials/"; - public const string Packages = Data + "/packages"; public const string CreatedPackages = Data + "/CreatedPackages"; diff --git a/src/Umbraco.Core/Constants-Telemetry.cs b/src/Umbraco.Core/Constants-Telemetry.cs index 52bf5d108f..7875abeb30 100644 --- a/src/Umbraco.Core/Constants-Telemetry.cs +++ b/src/Umbraco.Core/Constants-Telemetry.cs @@ -8,7 +8,6 @@ public static partial class Constants public static string DomainCount = "DomainCount"; public static string ExamineIndexCount = "ExamineIndexCount"; public static string LanguageCount = "LanguageCount"; - public static string MacroCount = "MacroCount"; public static string MediaCount = "MediaCount"; public static string MemberCount = "MemberCount"; public static string TemplateCount = "TemplateCount"; diff --git a/src/Umbraco.Core/Constants-UdiEntityType.cs b/src/Umbraco.Core/Constants-UdiEntityType.cs index beae3391b1..16b3ebe3b8 100644 --- a/src/Umbraco.Core/Constants-UdiEntityType.cs +++ b/src/Umbraco.Core/Constants-UdiEntityType.cs @@ -29,7 +29,6 @@ public static partial class Constants public const string Member = "member"; public const string DictionaryItem = "dictionary-item"; - public const string Macro = "macro"; public const string Template = "template"; public const string DocumentType = "document-type"; @@ -57,12 +56,10 @@ public static partial class Constants public const string AnyString = "any-string"; // that one is for tests public const string Language = "language"; - public const string MacroScript = "macroscript"; public const string MediaFile = "media-file"; public const string TemplateFile = "template-file"; public const string Script = "script"; public const string Stylesheet = "stylesheet"; public const string PartialView = "partial-view"; - public const string PartialViewMacro = "partial-view-macro"; } } diff --git a/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.cs b/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.cs index b968e029d4..744e02f001 100644 --- a/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.cs +++ b/src/Umbraco.Core/DependencyInjection/UmbracoBuilder.cs @@ -285,7 +285,6 @@ namespace Umbraco.Cms.Core.DependencyInjection Services.AddUnique(); Services.AddUnique(); Services.AddUnique(); - Services.AddUnique(); Services.AddUnique(); Services.AddUnique(); Services.AddUnique(); diff --git a/src/Umbraco.Core/Deploy/Direction.cs b/src/Umbraco.Core/Deploy/Direction.cs deleted file mode 100644 index a1129e2e4c..0000000000 --- a/src/Umbraco.Core/Deploy/Direction.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Umbraco.Cms.Core.Deploy; - -/// -/// Represents the direction when replacing an attribute value while parsing macros. -/// -public enum Direction -{ - /// - /// Replacing an attribute value while converting to an artifact. - /// - ToArtifact, - /// - /// Replacing an attribute value while converting from an artifact. - /// - FromArtifact, -} diff --git a/src/Umbraco.Core/Deploy/IMacroParser.cs b/src/Umbraco.Core/Deploy/IMacroParser.cs deleted file mode 100644 index de14bb528f..0000000000 --- a/src/Umbraco.Core/Deploy/IMacroParser.cs +++ /dev/null @@ -1,84 +0,0 @@ -namespace Umbraco.Cms.Core.Deploy; - -/// -/// Provides methods to parse macro tags in property values. -/// -public interface IMacroParser -{ - /// - /// Parses an Umbraco property value and produces an artifact property value. - /// - /// Property value. - /// A list of dependencies. - /// - /// Parsed value. - /// - [Obsolete("Please use the overload taking all parameters. This method will be removed in Umbraco 14.")] - string ToArtifact(string value, ICollection dependencies); - - /// - /// Parses an Umbraco property value and produces an artifact property value. - /// - /// Property value. - /// A list of dependencies. - /// The context cache. - /// - /// Parsed value. - /// - string ToArtifact(string value, ICollection dependencies, IContextCache contextCache) -#pragma warning disable CS0618 // Type or member is obsolete - => ToArtifact(value, dependencies); -#pragma warning restore CS0618 // Type or member is obsolete - - /// - /// Parses an artifact property value and produces an Umbraco property value. - /// - /// Artifact property value. - /// - /// Parsed value. - /// - [Obsolete("Please use the overload taking all parameters. This method will be removed in Umbraco 14.")] - string FromArtifact(string value); - - /// - /// Parses an artifact property value and produces an Umbraco property value. - /// - /// Artifact property value. - /// The context cache. - /// - /// Parsed value. - /// - string FromArtifact(string value, IContextCache contextCache) -#pragma warning disable CS0618 // Type or member is obsolete - => FromArtifact(value); -#pragma warning restore CS0618 // Type or member is obsolete - - /// - /// Tries to replace the value of the attribute/parameter with a value containing a converted identifier. - /// - /// Value to attempt to convert - /// Alias of the editor used for the parameter - /// Collection to add dependencies to when performing ToArtifact - /// Indicates which action is being performed (to or from artifact) - /// - /// Value with converted identifiers - /// - [Obsolete("Please use the overload taking all parameters. This method will be removed in Umbraco 14.")] - string ReplaceAttributeValue(string value, string editorAlias, ICollection dependencies, Direction direction); - - /// - /// Tries to replace the value of the attribute/parameter with a value containing a converted identifier. - /// - /// Value to attempt to convert - /// Alias of the editor used for the parameter - /// Collection to add dependencies to when performing ToArtifact - /// Indicates which action is being performed (to or from artifact) - /// The context cache. - /// - /// Value with converted identifiers - /// - string ReplaceAttributeValue(string value, string editorAlias, ICollection dependencies, Direction direction, IContextCache contextCache) -#pragma warning disable CS0618 // Type or member is obsolete - => ReplaceAttributeValue(value, editorAlias, dependencies, direction); -#pragma warning restore CS0618 // Type or member is obsolete -} diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/Breadcrumb.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/Breadcrumb.cshtml index 6a807e8379..612c809487 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/Breadcrumb.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/Breadcrumb.cshtml @@ -1,6 +1,6 @@ @using Umbraco.Cms.Core.Routing @using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @inject IPublishedUrlProvider PublishedUrlProvider @* This snippet makes a breadcrumb of parents using an unordered HTML list. diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/EditProfile.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/EditProfile.cshtml index 1b1ebd7284..596108fde3 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/EditProfile.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/EditProfile.cshtml @@ -1,4 +1,4 @@ -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @using Umbraco.Cms.Core.Services @using Umbraco.Cms.Web.Common.Security @using Umbraco.Cms.Web.Website.Controllers diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/Empty.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/Empty.cshtml index 01501b67a8..abafde104c 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/Empty.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/Empty.cshtml @@ -1 +1 @@ -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/Gallery.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/Gallery.cshtml deleted file mode 100644 index 83ac245500..0000000000 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/Gallery.cshtml +++ /dev/null @@ -1,57 +0,0 @@ -@using Umbraco.Cms.Core -@using Umbraco.Cms.Core.Media -@using Umbraco.Cms.Core.Models.PublishedContent -@using Umbraco.Cms.Core.Routing -@using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage -@inject IPublishedValueFallback PublishedValueFallback -@inject IPublishedContentQuery PublishedContentQuery -@inject IVariationContextAccessor VariationContextAccessor -@inject IPublishedUrlProvider PublishedUrlProvider -@inject IImageUrlGenerator ImageUrlGenerator - -@* - Macro to display a gallery of images from the Media section. - Works with either a 'Single Media Picker' or a 'Multiple Media Picker' macro parameter (see below). - - How it works: - - Confirm the macro parameter has been passed in with a value - - Loop through all the media Ids passed in (might be a single item, might be many) - - Display any individual images, as well as any folders of images - - Macro Parameters To Create, for this macro to work: - Alias:mediaIds Name:Select folders and/or images Type: Multiple Media Picker - Type: (note: You can use a Single Media Picker if that's more appropriate to your needs) -*@ - -@{ var mediaIds = Model?.MacroParameters["mediaIds"] as string; } - -@if (mediaIds != null) -{ -
- @foreach (var mediaId in mediaIds.Split(',')) - { - var media = PublishedContentQuery.Media(mediaId); - - @* a single image *@ - if (media.IsDocumentType("Image")) - { -
- - @media.Name - -
- } - - @* a folder with images under it *@ - foreach (var image in media.Children(VariationContextAccessor)) - { -
- - @image.Name - -
- } - } -
-} diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/ListAncestorsFromCurrentPage.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/ListAncestorsFromCurrentPage.cshtml index ead17cfe59..a005697666 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/ListAncestorsFromCurrentPage.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/ListAncestorsFromCurrentPage.cshtml @@ -1,6 +1,6 @@ @using Umbraco.Cms.Core.Routing @using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @inject IPublishedUrlProvider PublishedUrlProvider @* This snippet makes a list of links to the of parents of the current page using an unordered HTML list. diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesFromChangeableSource.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesFromChangeableSource.cshtml deleted file mode 100644 index a53c658364..0000000000 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesFromChangeableSource.cshtml +++ /dev/null @@ -1,38 +0,0 @@ -@using Umbraco.Cms.Core -@using Umbraco.Cms.Core.Models.PublishedContent -@using Umbraco.Cms.Core.Routing -@using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage -@inject IPublishedContentQuery PublishedContentQuery -@inject IPublishedValueFallback PublishedValueFallback -@inject IPublishedUrlProvider PublishedUrlProvider -@* - Macro to list all child pages under a specific page in the content tree. - - How it works: - - Confirm the startNodeId macro parameter has been passed in with a value - - Loop through all child pages - - Display a list of link to those pages, sorted by the value of the propertyAlias - - Macro Parameters To Create, for this macro to work: - Alias:startNodeId Name:Select starting page Type:Content Picker -*@ - -@{ var startNodeId = Model?.MacroParameters["startNodeId"]; } - -@if (startNodeId != null) -{ - @* Get the starting page *@ - var startNode = PublishedContentQuery.Content(startNodeId); - var selection = startNode.Children.Where(x => x.IsVisible(PublishedValueFallback)).ToArray(); - - if (selection.Length > 0) - { -
    - @foreach (var item in selection) - { -
  • @item.Name
  • - } -
- } -} diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesFromCurrentPage.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesFromCurrentPage.cshtml index 7b055e8424..2a88e47660 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesFromCurrentPage.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesFromCurrentPage.cshtml @@ -2,7 +2,7 @@ @using Umbraco.Cms.Core.Models.PublishedContent @using Umbraco.Cms.Core.Routing @using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @inject IPublishedValueFallback PublishedValueFallback @inject IPublishedUrlProvider PublishedUrlProvider @* diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByDate.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByDate.cshtml index 4b07c6209f..168e9b63ac 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByDate.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByDate.cshtml @@ -2,7 +2,7 @@ @using Umbraco.Cms.Core.Models.PublishedContent @using Umbraco.Cms.Core.Routing @using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @inject IPublishedValueFallback PublishedValueFallback @inject IPublishedUrlProvider PublishedUrlProvider @* diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByName.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByName.cshtml index f46bbcda80..aed9085a76 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByName.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByName.cshtml @@ -2,7 +2,7 @@ @using Umbraco.Cms.Core.Models.PublishedContent @using Umbraco.Cms.Core.Routing @using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @inject IPublishedValueFallback PublishedValueFallback @inject IPublishedUrlProvider PublishedUrlProvider @* diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByProperty.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByProperty.cshtml deleted file mode 100644 index 82b34ca55c..0000000000 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesOrderedByProperty.cshtml +++ /dev/null @@ -1,35 +0,0 @@ -@using Umbraco.Cms.Core -@using Umbraco.Cms.Core.Models.PublishedContent -@using Umbraco.Cms.Core.Routing -@using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage -@inject IPublishedValueFallback PublishedValueFallback -@inject IPublishedUrlProvider PublishedUrlProvider -@* - Macro to list all child pages with a specific property, sorted by the value of that property. - - How it works: - - Confirm the propertyAlias macro parameter has been passed in with a value - - Loop through all child pages that have the propertyAlias - - Display a list of link to those pages, sorted by the value of the propertyAlias - - Macro Parameters To Create, for this macro to work: - Alias:propertyAlias Name:Property Alias Type:Textbox -*@ - -@{ var propertyAlias = Model?.MacroParameters["propertyAlias"]; } - -@if (propertyAlias != null) -{ - var selection = Model?.Content.Children.Where(x => x.IsVisible(PublishedValueFallback)).OrderBy(x => x.Value(PublishedValueFallback, propertyAlias.ToString())).ToArray(); - - if (selection?.Length > 0) - { -
    - @foreach (var item in selection) - { -
  • @item.Name
  • - } -
- } -} diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesWithDoctype.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesWithDoctype.cshtml index 466aeacaa3..95a65d0af9 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesWithDoctype.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/ListChildPagesWithDoctype.cshtml @@ -2,7 +2,7 @@ @using Umbraco.Cms.Core.Models.PublishedContent @using Umbraco.Cms.Core.Routing @using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @inject IVariationContextAccessor VariationContextAccessor @inject IPublishedValueFallback PublishedValueFallback @inject IPublishedUrlProvider PublishedUrlProvider diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/ListDescendantsFromCurrentPage.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/ListDescendantsFromCurrentPage.cshtml index 339c0bc42d..455236ac03 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/ListDescendantsFromCurrentPage.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/ListDescendantsFromCurrentPage.cshtml @@ -2,7 +2,7 @@ @using Umbraco.Cms.Core.Models.PublishedContent @using Umbraco.Cms.Core.Routing @using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @inject IPublishedValueFallback PublishedValueFallback @inject IPublishedUrlProvider PublishedUrlProvider @* diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/ListImagesFromMediaFolder.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/ListImagesFromMediaFolder.cshtml deleted file mode 100644 index 8148612409..0000000000 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/ListImagesFromMediaFolder.cshtml +++ /dev/null @@ -1,38 +0,0 @@ -@using Umbraco.Cms.Core -@using Umbraco.Cms.Core.Routing -@using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage -@inject IPublishedContentQuery PublishedContentQuery -@inject IPublishedUrlProvider PublishedUrlProvider -@* - Macro to display a series of images from a media folder. - - How it works: - - Confirm the macro parameter has been passed in with a value - - Loop through all the media Ids passed in (might be a single item, might be many) - - Display any individual images, as well as any folders of images - - Macro Parameters To Create, for this macro to work: - Alias:mediaId Name:Select folder with images Type:Single Media Picker -*@ - -@{ var mediaId = Model?.MacroParameters["mediaId"]; } - -@if (mediaId != null) -{ - @* Get the media item associated with the id passed in *@ - var media = PublishedContentQuery.Media(mediaId); - var selection = media.Children.ToArray(); - - if (selection.Length > 0) - { -
    - @foreach (var item in selection) - { -
  • - @item.Name -
  • - } -
- } -} diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/Login.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/Login.cshtml index 7ba7f2acca..1ba652b687 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/Login.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/Login.cshtml @@ -1,4 +1,4 @@ -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @using Umbraco.Cms.Web.Common.Models @using Umbraco.Cms.Web.Common.Security diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/LoginStatus.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/LoginStatus.cshtml index 8f5477bca4..bbe6192908 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/LoginStatus.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/LoginStatus.cshtml @@ -1,4 +1,4 @@ -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @using Microsoft.AspNetCore.Http.Extensions @using Umbraco.Cms.Web.Common.Models @using Umbraco.Cms.Web.Website.Controllers diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/MultinodeTree-picker.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/MultinodeTree-picker.cshtml index e89f9e7076..eaf66d4803 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/MultinodeTree-picker.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/MultinodeTree-picker.cshtml @@ -1,7 +1,7 @@ @using Umbraco.Cms.Core.Models.PublishedContent @using Umbraco.Cms.Core.Routing @using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @inject IPublishedValueFallback PublishedValueFallback @inject IPublishedUrlProvider PublishedUrlProvider @* diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/Navigation.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/Navigation.cshtml index 4343493511..7539707670 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/Navigation.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/Navigation.cshtml @@ -2,7 +2,7 @@ @using Umbraco.Cms.Core.Models.PublishedContent @using Umbraco.Cms.Core.Routing @using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @inject IPublishedValueFallback PublishedValueFallback @inject IPublishedUrlProvider PublishedUrlProvider @* diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/RegisterMember.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/RegisterMember.cshtml index f3b9e31254..db66e6501c 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/RegisterMember.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/RegisterMember.cshtml @@ -1,4 +1,4 @@ -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @using Microsoft.AspNetCore.Http.Extensions @using Umbraco.Cms.Core @using Umbraco.Cms.Core.Security @@ -84,6 +84,6 @@ else } - + } } diff --git a/src/Umbraco.Core/EmbeddedResources/Snippets/SiteMap.cshtml b/src/Umbraco.Core/EmbeddedResources/Snippets/SiteMap.cshtml index 3e4c30a376..3a257cc161 100644 --- a/src/Umbraco.Core/EmbeddedResources/Snippets/SiteMap.cshtml +++ b/src/Umbraco.Core/EmbeddedResources/Snippets/SiteMap.cshtml @@ -2,7 +2,7 @@ @using Umbraco.Cms.Core.Models.PublishedContent @using Umbraco.Cms.Core.Routing @using Umbraco.Extensions -@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @inject IPublishedValueFallback PublishedValueFallback @inject IPublishedUrlProvider PublishedUrlProvider @* diff --git a/src/Umbraco.Core/Events/MacroErrorEventArgs.cs b/src/Umbraco.Core/Events/MacroErrorEventArgs.cs deleted file mode 100644 index 876f7b99eb..0000000000 --- a/src/Umbraco.Core/Events/MacroErrorEventArgs.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Umbraco.Cms.Core.Macros; - -namespace Umbraco.Cms.Core.Events; - -// Provides information on the macro that caused an error -public class MacroErrorEventArgs : EventArgs -{ - /// - /// Name of the faulting macro. - /// - public string? Name { get; set; } - - /// - /// Alias of the faulting macro. - /// - public string? Alias { get; set; } - - /// - /// Filename, file path, fully qualified class name, or other key used by the macro engine to do it's processing of the - /// faulting macro. - /// - public string? MacroSource { get; set; } - - /// - /// Exception raised. - /// - public Exception? Exception { get; set; } - - /// - /// Gets or sets the desired behaviour when a matching macro causes an error. See - /// for definitions. By setting this in your event - /// you can override the default behaviour defined in UmbracoSettings.config. - /// - /// Macro error behaviour enum. - public MacroErrorBehaviour Behaviour { get; set; } - - /// - /// The HTML code to display when Behavior is Content. - /// - public string? Html { get; set; } -} diff --git a/src/Umbraco.Core/Extensions/UdiGetterExtensions.cs b/src/Umbraco.Core/Extensions/UdiGetterExtensions.cs index 9ddaeb22a5..9821f7d6b7 100644 --- a/src/Umbraco.Core/Extensions/UdiGetterExtensions.cs +++ b/src/Umbraco.Core/Extensions/UdiGetterExtensions.cs @@ -251,20 +251,6 @@ public static class UdiGetterExtensions return new GuidUdi(Constants.UdiEntityType.DictionaryItem, entity.Key).EnsureClosed(); } - /// - /// Gets the entity identifier of the entity. - /// - /// The entity. - /// - /// The entity identifier of the entity. - /// - public static GuidUdi GetUdi(this IMacro entity) - { - ArgumentNullException.ThrowIfNull(entity); - - return new GuidUdi(Constants.UdiEntityType.Macro, entity.Key).EnsureClosed(); - } - /// /// Gets the entity identifier of the entity. /// @@ -276,14 +262,7 @@ public static class UdiGetterExtensions { ArgumentNullException.ThrowIfNull(entity); - // TODO: We should throw on Unknown, but for the time being, assume it means PartialView - string entityType = entity.ViewType switch - { - PartialViewType.PartialViewMacro => Constants.UdiEntityType.PartialViewMacro, - _ => Constants.UdiEntityType.PartialView, - }; - - return GetUdiFromPath(entityType, entity.Path); + return GetUdiFromPath(Constants.UdiEntityType.PartialView, entity.Path); } /// @@ -381,7 +360,6 @@ public static class UdiGetterExtensions IDataType dataTypeComposition => dataTypeComposition.GetUdi(), IDictionaryItem dictionaryItem => dictionaryItem.GetUdi(), ILanguage language => language.GetUdi(), - IMacro macro => macro.GetUdi(), IMemberGroup memberGroup => memberGroup.GetUdi(), IPartialView partialView => partialView.GetUdi(), IRelationType relationType => relationType.GetUdi(), diff --git a/src/Umbraco.Core/HealthChecks/Checks/Configuration/MacroErrorsCheck.cs b/src/Umbraco.Core/HealthChecks/Checks/Configuration/MacroErrorsCheck.cs deleted file mode 100644 index a212a69a3e..0000000000 --- a/src/Umbraco.Core/HealthChecks/Checks/Configuration/MacroErrorsCheck.cs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) Umbraco. -// See LICENSE for more details. - -using Microsoft.Extensions.Options; -using Umbraco.Cms.Core.Configuration.Models; -using Umbraco.Cms.Core.Macros; -using Umbraco.Cms.Core.Services; -using Umbraco.Extensions; - -namespace Umbraco.Cms.Core.HealthChecks.Checks.Configuration; - -/// -/// Health check for the recommended production configuration for Macro Errors. -/// -[HealthCheck( - "D0F7599E-9B2A-4D9E-9883-81C7EDC5616F", - "Macro errors", - Description = "Checks to make sure macro errors are not set to throw a YSOD (yellow screen of death), which would prevent certain or all pages from loading completely.", - Group = "Configuration")] -public class MacroErrorsCheck : AbstractSettingsCheck -{ - private readonly IOptionsMonitor _contentSettings; - private readonly ILocalizedTextService _textService; - - /// - /// Initializes a new instance of the class. - /// - public MacroErrorsCheck( - ILocalizedTextService textService, - IOptionsMonitor contentSettings) - : base(textService) - { - _textService = textService; - _contentSettings = contentSettings; - } - - /// - public override string ReadMoreLink => Constants.HealthChecks.DocumentationLinks.Configuration.MacroErrorsCheck; - - /// - public override ValueComparisonType ValueComparisonType => ValueComparisonType.ShouldEqual; - - /// - public override string ItemPath => Constants.Configuration.ConfigContentMacroErrors; - - /// - /// Gets the values to compare against. - /// - public override IEnumerable Values - { - get - { - var values = new List - { - new() { IsRecommended = true, Value = MacroErrorBehaviour.Inline.ToString() }, - new() { IsRecommended = false, Value = MacroErrorBehaviour.Silent.ToString() }, - }; - - return values; - } - } - - /// - public override string CurrentValue => _contentSettings.CurrentValue.MacroErrors.ToString(); - - /// - /// Gets the message for when the check has succeeded. - /// - public override string CheckSuccessMessage => - _textService.Localize( - "healthcheck", "macroErrorModeCheckSuccessMessage", new[] { CurrentValue, Values.First(v => v.IsRecommended).Value }); - - /// - /// Gets the message for when the check has failed. - /// - public override string CheckErrorMessage => - _textService.Localize( - "healthcheck", "macroErrorModeCheckErrorMessage", new[] { CurrentValue, Values.First(v => v.IsRecommended).Value }); -} diff --git a/src/Umbraco.Core/IO/FileSystems.cs b/src/Umbraco.Core/IO/FileSystems.cs index 69b66dc270..3e40398382 100644 --- a/src/Umbraco.Core/IO/FileSystems.cs +++ b/src/Umbraco.Core/IO/FileSystems.cs @@ -19,7 +19,6 @@ namespace Umbraco.Cms.Core.IO // wrappers for shadow support - private ShadowWrapper? _macroPartialFileSystem; private ShadowWrapper? _partialViewsFileSystem; private ShadowWrapper? _stylesheetsFileSystem; private ShadowWrapper? _scriptsFileSystem; @@ -56,13 +55,11 @@ namespace Umbraco.Cms.Core.IO IIOHelper ioHelper, IOptions globalSettings, IHostingEnvironment hostingEnvironment, - IFileSystem macroPartialFileSystem, IFileSystem partialViewsFileSystem, IFileSystem stylesheetFileSystem, IFileSystem scriptsFileSystem, IFileSystem mvcViewFileSystem) : this(loggerFactory, ioHelper, globalSettings, hostingEnvironment) { - _macroPartialFileSystem = CreateShadowWrapperInternal(macroPartialFileSystem, "macro-partials"); _partialViewsFileSystem = CreateShadowWrapperInternal(partialViewsFileSystem, "partials"); _stylesheetsFileSystem = CreateShadowWrapperInternal(stylesheetFileSystem, "css"); _scriptsFileSystem = CreateShadowWrapperInternal(scriptsFileSystem, "scripts"); @@ -82,22 +79,6 @@ namespace Umbraco.Cms.Core.IO #region Well-Known FileSystems - /// - /// Gets the macro partials filesystem. - /// - public IFileSystem? MacroPartialsFileSystem - { - get - { - if (Volatile.Read(ref _wkfsInitialized) == false) - { - EnsureWellKnownFileSystems(); - } - - return _macroPartialFileSystem; - } - } - /// /// Gets the partial views filesystem. /// @@ -214,12 +195,10 @@ namespace Umbraco.Cms.Core.IO ILogger logger = _loggerFactory.CreateLogger(); //TODO this is fucked, why do PhysicalFileSystem has a root url? Mvc views cannot be accessed by url! - var macroPartialFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, logger, _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MacroPartials), _hostingEnvironment.ToAbsolute(Constants.SystemDirectories.MacroPartials)); var partialViewsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, logger, _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.PartialViews), _hostingEnvironment.ToAbsolute(Constants.SystemDirectories.PartialViews)); var scriptsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, logger, _hostingEnvironment.MapPathWebRoot(_globalSettings.UmbracoScriptsPath), _hostingEnvironment.ToAbsolute(_globalSettings.UmbracoScriptsPath)); var mvcViewsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, logger, _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MvcViews), _hostingEnvironment.ToAbsolute(Constants.SystemDirectories.MvcViews)); - _macroPartialFileSystem = new ShadowWrapper(macroPartialFileSystem, _ioHelper, _hostingEnvironment, _loggerFactory, "macro-partials", IsScoped); _partialViewsFileSystem = new ShadowWrapper(partialViewsFileSystem, _ioHelper, _hostingEnvironment, _loggerFactory, "partials", IsScoped); _scriptsFileSystem = new ShadowWrapper(scriptsFileSystem, _ioHelper, _hostingEnvironment, _loggerFactory, "scripts", IsScoped); _mvcViewsFileSystem = new ShadowWrapper(mvcViewsFileSystem, _ioHelper, _hostingEnvironment, _loggerFactory, "views", IsScoped); @@ -239,7 +218,6 @@ namespace Umbraco.Cms.Core.IO } // TODO: do we need a lock here? - _shadowWrappers.Add(_macroPartialFileSystem); _shadowWrappers.Add(_partialViewsFileSystem); _shadowWrappers.Add(_scriptsFileSystem); _shadowWrappers.Add(_mvcViewsFileSystem); diff --git a/src/Umbraco.Core/Macros/IMacroRenderer.cs b/src/Umbraco.Core/Macros/IMacroRenderer.cs deleted file mode 100644 index f1e7d8c383..0000000000 --- a/src/Umbraco.Core/Macros/IMacroRenderer.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Umbraco.Cms.Core.Models.PublishedContent; - -namespace Umbraco.Cms.Core.Macros; - -/// -/// Renders a macro -/// -public interface IMacroRenderer -{ - Task RenderAsync(string macroAlias, IPublishedContent? content, IDictionary? macroParams); -} diff --git a/src/Umbraco.Core/Macros/MacroContent.cs b/src/Umbraco.Core/Macros/MacroContent.cs deleted file mode 100644 index c36c630168..0000000000 --- a/src/Umbraco.Core/Macros/MacroContent.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Umbraco.Cms.Core.Macros; - -// represents the content of a macro -public class MacroContent -{ - // gets an empty macro content - public static MacroContent Empty { get; } = new(); - - // gets or sets the text content - public string? Text { get; set; } - - // gets or sets the date the content was generated - public DateTime Date { get; set; } = DateTime.Now; - - // a value indicating whether the content is empty - public bool IsEmpty => Text is null; -} diff --git a/src/Umbraco.Core/Macros/MacroErrorBehaviour.cs b/src/Umbraco.Core/Macros/MacroErrorBehaviour.cs deleted file mode 100644 index 49a53f11b0..0000000000 --- a/src/Umbraco.Core/Macros/MacroErrorBehaviour.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace Umbraco.Cms.Core.Macros; - -public enum MacroErrorBehaviour -{ - /// - /// Default umbraco behavior - show an inline error within the - /// macro but allow the page to continue rendering. - /// - Inline, - - /// - /// Silently eat the error and do not display the offending macro. - /// - Silent, - - /// - /// Throw an exception which can be caught by the global error handler - /// defined in Application_OnError. If no such error handler is defined - /// then you'll see the Yellow Screen Of Death (YSOD) error page. - /// - Throw, - - /// - /// Silently eat the error and display the custom content reported in - /// the error event args - /// - Content, -} diff --git a/src/Umbraco.Core/Macros/MacroModel.cs b/src/Umbraco.Core/Macros/MacroModel.cs deleted file mode 100644 index 12649bf91c..0000000000 --- a/src/Umbraco.Core/Macros/MacroModel.cs +++ /dev/null @@ -1,61 +0,0 @@ -using Umbraco.Cms.Core.Models; - -namespace Umbraco.Cms.Core.Macros; - -public class MacroModel -{ - public MacroModel() - { - } - - public MacroModel(IMacro? macro) - { - if (macro == null) - { - return; - } - - Id = macro.Id; - Name = macro.Name; - Alias = macro.Alias; - MacroSource = macro.MacroSource; - CacheDuration = macro.CacheDuration; - CacheByPage = macro.CacheByPage; - CacheByMember = macro.CacheByMember; - RenderInEditor = macro.UseInEditor; - - foreach (IMacroProperty prop in macro.Properties) - { - Properties.Add(new MacroPropertyModel(prop.Alias, string.Empty, prop.EditorAlias)); - } - } - - /// - /// The Macro Id - /// - public int Id { get; set; } - - /// - /// The Macro Name - /// - public string? Name { get; set; } - - /// - /// The Macro Alias - /// - public string? Alias { get; set; } - - public string? MacroSource { get; set; } - - public int CacheDuration { get; set; } - - public bool CacheByPage { get; set; } - - public bool CacheByMember { get; set; } - - public bool RenderInEditor { get; set; } - - public string? CacheIdentifier { get; set; } - - public List Properties { get; } = new(); -} diff --git a/src/Umbraco.Core/Macros/MacroPropertyModel.cs b/src/Umbraco.Core/Macros/MacroPropertyModel.cs deleted file mode 100644 index c1022c3561..0000000000 --- a/src/Umbraco.Core/Macros/MacroPropertyModel.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace Umbraco.Cms.Core.Macros; - -public class MacroPropertyModel -{ - public MacroPropertyModel() => Key = string.Empty; - - public MacroPropertyModel(string key, string value) - { - Key = key; - Value = value; - } - - public MacroPropertyModel(string key, string value, string type) - { - Key = key; - Value = value; - Type = type; - } - - public string Key { get; set; } - - public string? Value { get; set; } - - public string? Type { get; set; } -} diff --git a/src/Umbraco.Core/Models/ContentEditing/EntityBasic.cs b/src/Umbraco.Core/Models/ContentEditing/EntityBasic.cs index 36a837e8e8..62bce70f86 100644 --- a/src/Umbraco.Core/Models/ContentEditing/EntityBasic.cs +++ b/src/Umbraco.Core/Models/ContentEditing/EntityBasic.cs @@ -45,7 +45,7 @@ public class EntityBasic public int ParentId { get; set; } /// - /// This will only be populated for some entities like macros + /// This will only be populated for some entities /// /// /// It is possible to override this to specify different validation attributes if required diff --git a/src/Umbraco.Core/Models/ContentEditing/MacroDisplay.cs b/src/Umbraco.Core/Models/ContentEditing/MacroDisplay.cs deleted file mode 100644 index 9919004a50..0000000000 --- a/src/Umbraco.Core/Models/ContentEditing/MacroDisplay.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.Runtime.Serialization; - -namespace Umbraco.Cms.Core.Models.ContentEditing; - -/// -/// The macro display model -/// -[DataContract(Name = "dictionary", Namespace = "")] -public class MacroDisplay : EntityBasic, INotificationModel -{ - /// - /// Initializes a new instance of the class. - /// - public MacroDisplay() - { - Notifications = new List(); - Parameters = new List(); - } - - /// - /// Gets or sets a value indicating whether the macro can be used in a rich text editor. - /// - [DataMember(Name = "useInEditor")] - public bool UseInEditor { get; set; } - - /// - /// Gets or sets a value indicating whether the macro should be rendered a rich text editor. - /// - [DataMember(Name = "renderInEditor")] - public bool RenderInEditor { get; set; } - - /// - /// Gets or sets the cache period. - /// - [DataMember(Name = "cachePeriod")] - public int CachePeriod { get; set; } - - /// - /// Gets or sets a value indicating whether the macro should be cached by page - /// - [DataMember(Name = "cacheByPage")] - public bool CacheByPage { get; set; } - - /// - /// Gets or sets a value indicating whether the macro should be cached by user - /// - [DataMember(Name = "cacheByUser")] - public bool CacheByUser { get; set; } - - /// - /// Gets or sets the view. - /// - [DataMember(Name = "view")] - public string View { get; set; } = null!; - - /// - /// Gets or sets the parameters. - /// - [DataMember(Name = "parameters")] - public IEnumerable Parameters { get; set; } - - /// - [DataMember(Name = "notifications")] - public List Notifications { get; } -} diff --git a/src/Umbraco.Core/Models/ContentEditing/MacroParameter.cs b/src/Umbraco.Core/Models/ContentEditing/MacroParameter.cs deleted file mode 100644 index 3db1cd5820..0000000000 --- a/src/Umbraco.Core/Models/ContentEditing/MacroParameter.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.ComponentModel.DataAnnotations; -using System.Runtime.Serialization; - -namespace Umbraco.Cms.Core.Models.ContentEditing; - -/// -/// Represents a macro parameter with an editor -/// -[DataContract(Name = "macroParameter", Namespace = "")] -public class MacroParameter -{ - [DataMember(Name = "alias", IsRequired = true)] - [Required] - public string Alias { get; set; } = null!; - - [DataMember(Name = "name")] - public string? Name { get; set; } - - [DataMember(Name = "sortOrder")] - public int SortOrder { get; set; } - - /// - /// The editor view to render for this parameter - /// - [DataMember(Name = "view", IsRequired = true)] - [Required(AllowEmptyStrings = false)] - public string? View { get; set; } - - /// - /// The configuration for this parameter editor - /// - [DataMember(Name = "config", IsRequired = true)] - [Required(AllowEmptyStrings = false)] - public IDictionary? Configuration { get; set; } - - /// - /// Since we don't post this back this isn't currently really used on the server side - /// - [DataMember(Name = "value")] - public object? Value { get; set; } -} diff --git a/src/Umbraco.Core/Models/ContentEditing/MacroParameterDisplay.cs b/src/Umbraco.Core/Models/ContentEditing/MacroParameterDisplay.cs deleted file mode 100644 index 3a532fcc12..0000000000 --- a/src/Umbraco.Core/Models/ContentEditing/MacroParameterDisplay.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Runtime.Serialization; - -namespace Umbraco.Cms.Core.Models.ContentEditing; - -/// -/// The macro parameter display. -/// -[DataContract(Name = "parameter", Namespace = "")] -public class MacroParameterDisplay -{ - /// - /// Gets or sets the key. - /// - [DataMember(Name = "key")] - public string Key { get; set; } = null!; - - /// - /// Gets or sets the label. - /// - [DataMember(Name = "label")] - public string? Label { get; set; } - - /// - /// Gets or sets the editor. - /// - [DataMember(Name = "editor")] - public string Editor { get; set; } = null!; - - /// - /// Gets or sets the id. - /// - [DataMember(Name = "id")] - public int Id { get; set; } -} diff --git a/src/Umbraco.Core/Models/ContentEditing/UmbracoEntityTypes.cs b/src/Umbraco.Core/Models/ContentEditing/UmbracoEntityTypes.cs index e089093174..ba4b2d8a5b 100644 --- a/src/Umbraco.Core/Models/ContentEditing/UmbracoEntityTypes.cs +++ b/src/Umbraco.Core/Models/ContentEditing/UmbracoEntityTypes.cs @@ -15,11 +15,6 @@ public enum UmbracoEntityTypes /// User, - /// - /// Macro - /// - Macro, - /// /// Document /// diff --git a/src/Umbraco.Core/Models/IContentModel.cs b/src/Umbraco.Core/Models/IContentModel.cs index c7669dfbe4..f12cf30ecc 100644 --- a/src/Umbraco.Core/Models/IContentModel.cs +++ b/src/Umbraco.Core/Models/IContentModel.cs @@ -8,8 +8,7 @@ namespace Umbraco.Cms.Core.Models; /// /// /// exists in order to unify all view models in Umbraco, whether it's a normal -/// template view or a partial view macro, or -/// a user's custom model that they have created when doing route hijacking or custom routes. +/// template view or a user's custom model that they have created when doing route hijacking or custom routes. /// /// /// By default all front-end template views inherit from UmbracoViewPage which has a model of diff --git a/src/Umbraco.Core/Models/IMacro.cs b/src/Umbraco.Core/Models/IMacro.cs deleted file mode 100644 index bc979804a7..0000000000 --- a/src/Umbraco.Core/Models/IMacro.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Runtime.Serialization; -using Umbraco.Cms.Core.Models.Entities; - -namespace Umbraco.Cms.Core.Models; - -/// -/// Defines a Macro -/// -public interface IMacro : IEntity, IRememberBeingDirty -{ - /// - /// Gets or sets the alias of the Macro - /// - [DataMember] - string Alias { get; set; } - - /// - /// Gets or sets the name of the Macro - /// - [DataMember] - string? Name { get; set; } - - /// - /// Gets or sets a boolean indicating whether the Macro can be used in an Editor - /// - [DataMember] - bool UseInEditor { get; set; } - - /// - /// Gets or sets the Cache Duration for the Macro - /// - [DataMember] - int CacheDuration { get; set; } - - /// - /// Gets or sets a boolean indicating whether the Macro should be Cached by Page - /// - [DataMember] - bool CacheByPage { get; set; } - - /// - /// Gets or sets a boolean indicating whether the Macro should be Cached Personally - /// - [DataMember] - bool CacheByMember { get; set; } - - /// - /// Gets or sets a boolean indicating whether the Macro should be rendered in an Editor - /// - [DataMember] - bool DontRender { get; set; } - - /// - /// Gets or set the path to the macro source to render - /// - [DataMember] - string MacroSource { get; set; } - - /// - /// Gets or sets a list of Macro Properties - /// - [DataMember] - MacroPropertyCollection Properties { get; } -} diff --git a/src/Umbraco.Core/Models/IMacroProperty.cs b/src/Umbraco.Core/Models/IMacroProperty.cs deleted file mode 100644 index e1b27b6483..0000000000 --- a/src/Umbraco.Core/Models/IMacroProperty.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Runtime.Serialization; -using Umbraco.Cms.Core.Models.Entities; - -namespace Umbraco.Cms.Core.Models; - -/// -/// Defines a Property for a Macro -/// -public interface IMacroProperty : IValueObject, IDeepCloneable, IRememberBeingDirty -{ - [DataMember] - int Id { get; set; } - - [DataMember] - Guid Key { get; set; } - - /// - /// Gets or sets the Alias of the Property - /// - [DataMember] - string Alias { get; set; } - - /// - /// Gets or sets the Name of the Property - /// - [DataMember] - string? Name { get; set; } - - /// - /// Gets or sets the Sort Order of the Property - /// - [DataMember] - int SortOrder { get; set; } - - /// - /// Gets or sets the parameter editor alias - /// - [DataMember] - string EditorAlias { get; set; } -} diff --git a/src/Umbraco.Core/Models/IPartialView.cs b/src/Umbraco.Core/Models/IPartialView.cs index a19cc65c7a..d37b2af415 100644 --- a/src/Umbraco.Core/Models/IPartialView.cs +++ b/src/Umbraco.Core/Models/IPartialView.cs @@ -2,5 +2,4 @@ namespace Umbraco.Cms.Core.Models; public interface IPartialView : IFile { - PartialViewType ViewType { get; } } diff --git a/src/Umbraco.Core/Models/Macro.cs b/src/Umbraco.Core/Models/Macro.cs deleted file mode 100644 index ea03750e32..0000000000 --- a/src/Umbraco.Core/Models/Macro.cs +++ /dev/null @@ -1,287 +0,0 @@ -using System.Collections.Specialized; -using System.ComponentModel; -using System.Runtime.Serialization; -using Umbraco.Cms.Core.Models.Entities; -using Umbraco.Cms.Core.Strings; -using Umbraco.Extensions; - -namespace Umbraco.Cms.Core.Models; - -/// -/// Represents a Macro -/// -[Serializable] -[DataContract(IsReference = true)] -public class Macro : EntityBase, IMacro -{ - private readonly IShortStringHelper _shortStringHelper; - private List _addedProperties; - - private string _alias; - private bool _cacheByMember; - private bool _cacheByPage; - private int _cacheDuration; - private bool _dontRender; - private string _macroSource; - private string? _name; - private List _removedProperties; - private bool _useInEditor; - - public Macro(IShortStringHelper shortStringHelper) - { - _alias = string.Empty; - _shortStringHelper = shortStringHelper; - Properties = new MacroPropertyCollection(); - Properties.CollectionChanged += PropertiesChanged; - _addedProperties = new List(); - _removedProperties = new List(); - _macroSource = string.Empty; - } - - /// - /// Creates an item with pre-filled properties - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public Macro( - IShortStringHelper shortStringHelper, - int id, - Guid key, - bool useInEditor, - int cacheDuration, - string alias, - string? name, - bool cacheByPage, - bool cacheByMember, - bool dontRender, - string macroSource) - : this(shortStringHelper) - { - Id = id; - Key = key; - UseInEditor = useInEditor; - CacheDuration = cacheDuration; - Alias = alias.ToCleanString(shortStringHelper, CleanStringType.Alias); - Name = name; - CacheByPage = cacheByPage; - CacheByMember = cacheByMember; - DontRender = dontRender; - MacroSource = macroSource; - } - - /// - /// Creates an instance for persisting a new item - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public Macro( - IShortStringHelper shortStringHelper, - string alias, - string? name, - string macroSource, - bool cacheByPage = false, - bool cacheByMember = false, - bool dontRender = true, - bool useInEditor = false, - int cacheDuration = 0) - : this(shortStringHelper) - { - UseInEditor = useInEditor; - CacheDuration = cacheDuration; - Alias = alias.ToCleanString(shortStringHelper, CleanStringType.Alias); - Name = name; - CacheByPage = cacheByPage; - CacheByMember = cacheByMember; - DontRender = dontRender; - MacroSource = macroSource; - } - - /// - /// Gets or sets the alias of the Macro - /// - [DataMember] - public string Alias - { - get => _alias; - set => SetPropertyValueAndDetectChanges( - value.ToCleanString(_shortStringHelper, CleanStringType.Alias), - ref _alias!, - nameof(Alias)); - } - - /// - /// Used internally to check if we need to add a section in the repository to the db - /// - internal IEnumerable AddedProperties => _addedProperties; - - /// - /// Used internally to check if we need to remove a section in the repository to the db - /// - internal IEnumerable RemovedProperties => _removedProperties; - - public override void ResetDirtyProperties(bool rememberDirty) - { - base.ResetDirtyProperties(rememberDirty); - - _addedProperties.Clear(); - _removedProperties.Clear(); - - foreach (IMacroProperty prop in Properties) - { - prop.ResetDirtyProperties(rememberDirty); - } - } - - /// - /// Gets or sets the name of the Macro - /// - [DataMember] - public string? Name - { - get => _name; - set => SetPropertyValueAndDetectChanges(value, ref _name, nameof(Name)); - } - - /// - /// Gets or sets a boolean indicating whether the Macro can be used in an Editor - /// - [DataMember] - public bool UseInEditor - { - get => _useInEditor; - set => SetPropertyValueAndDetectChanges(value, ref _useInEditor, nameof(UseInEditor)); - } - - /// - /// Gets or sets the Cache Duration for the Macro - /// - [DataMember] - public int CacheDuration - { - get => _cacheDuration; - set => SetPropertyValueAndDetectChanges(value, ref _cacheDuration, nameof(CacheDuration)); - } - - /// - /// Gets or sets a boolean indicating whether the Macro should be Cached by Page - /// - [DataMember] - public bool CacheByPage - { - get => _cacheByPage; - set => SetPropertyValueAndDetectChanges(value, ref _cacheByPage, nameof(CacheByPage)); - } - - /// - /// Gets or sets a boolean indicating whether the Macro should be Cached Personally - /// - [DataMember] - public bool CacheByMember - { - get => _cacheByMember; - set => SetPropertyValueAndDetectChanges(value, ref _cacheByMember, nameof(CacheByMember)); - } - - /// - /// Gets or sets a boolean indicating whether the Macro should be rendered in an Editor - /// - [DataMember] - public bool DontRender - { - get => _dontRender; - set => SetPropertyValueAndDetectChanges(value, ref _dontRender, nameof(DontRender)); - } - - /// - /// Gets or set the path to the Partial View to render - /// - [DataMember] - public string MacroSource - { - get => _macroSource; - set => SetPropertyValueAndDetectChanges(value, ref _macroSource!, nameof(MacroSource)); - } - - /// - /// Gets or sets a list of Macro Properties - /// - [DataMember] - public MacroPropertyCollection Properties { get; private set; } - - protected override void PerformDeepClone(object clone) - { - base.PerformDeepClone(clone); - - var clonedEntity = (Macro)clone; - - clonedEntity._addedProperties = new List(); - clonedEntity._removedProperties = new List(); - clonedEntity.Properties = (MacroPropertyCollection)Properties.DeepClone(); - - // re-assign the event handler - clonedEntity.Properties.CollectionChanged += clonedEntity.PropertiesChanged; - } - - private void PropertiesChanged(object? sender, NotifyCollectionChangedEventArgs e) - { - OnPropertyChanged(nameof(Properties)); - - if (e.Action == NotifyCollectionChangedAction.Add) - { - // listen for changes - MacroProperty? prop = e.NewItems?.Cast().First(); - if (prop is not null) - { - prop.PropertyChanged += PropertyDataChanged; - - var alias = prop.Alias; - - if (_addedProperties.Contains(alias) == false) - { - // add to the added props - _addedProperties.Add(alias); - } - } - } - else if (e.Action == NotifyCollectionChangedAction.Remove) - { - // remove listening for changes - MacroProperty? prop = e.OldItems?.Cast().First(); - if (prop is not null) - { - prop.PropertyChanged -= PropertyDataChanged; - - var alias = prop.Alias; - - if (_removedProperties.Contains(alias) == false) - { - _removedProperties.Add(alias); - } - } - } - } - - /// - /// When some data of a property has changed ensure our Properties flag is dirty - /// - /// - /// - private void PropertyDataChanged(object? sender, PropertyChangedEventArgs e) => - OnPropertyChanged(nameof(Properties)); -} diff --git a/src/Umbraco.Core/Models/MacroProperty.cs b/src/Umbraco.Core/Models/MacroProperty.cs deleted file mode 100644 index 2a6f041fc0..0000000000 --- a/src/Umbraco.Core/Models/MacroProperty.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System.Runtime.Serialization; -using Umbraco.Cms.Core.Models.Entities; - -namespace Umbraco.Cms.Core.Models; - -/// -/// Represents a Macro Property -/// -[Serializable] -[DataContract(IsReference = true)] -public class MacroProperty : BeingDirtyBase, IMacroProperty -{ - private string _alias; - private string _editorAlias; - private int _id; - - private Guid _key; - private string? _name; - private int _sortOrder; - - public MacroProperty() - { - _editorAlias = string.Empty; - _alias = string.Empty; - _key = Guid.NewGuid(); - } - - /// - /// Ctor for creating a new property - /// - /// - /// - /// - /// - public MacroProperty(string alias, string? name, int sortOrder, string editorAlias) - { - _alias = alias; - _name = name; - _sortOrder = sortOrder; - _key = Guid.NewGuid(); - _editorAlias = editorAlias; - } - - /// - /// Ctor for creating an existing property - /// - /// - /// - /// - /// - /// - /// - public MacroProperty(int id, Guid key, string alias, string? name, int sortOrder, string editorAlias) - { - _id = id; - _alias = alias; - _name = name; - _sortOrder = sortOrder; - _key = key; - _editorAlias = editorAlias; - } - - /// - /// Gets or sets the Key of the Property - /// - [DataMember] - public Guid Key - { - get => _key; - set => SetPropertyValueAndDetectChanges(value, ref _key, nameof(Key)); - } - - /// - /// Gets or sets the Alias of the Property - /// - [DataMember] - public int Id - { - get => _id; - set => SetPropertyValueAndDetectChanges(value, ref _id, nameof(Id)); - } - - /// - /// Gets or sets the Alias of the Property - /// - [DataMember] - public string Alias - { - get => _alias; - set => SetPropertyValueAndDetectChanges(value, ref _alias!, nameof(Alias)); - } - - /// - /// Gets or sets the Name of the Property - /// - [DataMember] - public string? Name - { - get => _name; - set => SetPropertyValueAndDetectChanges(value, ref _name, nameof(Name)); - } - - /// - /// Gets or sets the Sort Order of the Property - /// - [DataMember] - public int SortOrder - { - get => _sortOrder; - set => SetPropertyValueAndDetectChanges(value, ref _sortOrder, nameof(SortOrder)); - } - - /// - /// Gets or sets the Type for this Property - /// - /// - /// The MacroPropertyTypes acts as a plugin for Macros. - /// All types was previously contained in the database, but has been ported to code. - /// - [DataMember] - public string EditorAlias - { - get => _editorAlias; - set => SetPropertyValueAndDetectChanges(value, ref _editorAlias!, nameof(EditorAlias)); - } - - public object DeepClone() - { - // Memberwise clone on MacroProperty will work since it doesn't have any deep elements - // for any sub class this will work for standard properties as well that aren't complex object's themselves. - var clone = (MacroProperty)MemberwiseClone(); - - // Automatically deep clone ref properties that are IDeepCloneable - DeepCloneHelper.DeepCloneRefProperties(this, clone); - clone.ResetDirtyProperties(false); - return clone; - } - - public override bool Equals(object? obj) - { - if (ReferenceEquals(null, obj)) - { - return false; - } - - if (ReferenceEquals(this, obj)) - { - return true; - } - - if (obj.GetType() != GetType()) - { - return false; - } - - return Equals((MacroProperty)obj); - } - - protected bool Equals(MacroProperty other) => string.Equals(_alias, other._alias) && _id == other._id; - - public override int GetHashCode() - { - unchecked - { - return ((_alias != null ? _alias.GetHashCode() : 0) * 397) ^ _id; - } - } -} diff --git a/src/Umbraco.Core/Models/MacroPropertyCollection.cs b/src/Umbraco.Core/Models/MacroPropertyCollection.cs deleted file mode 100644 index c31cc8cbc1..0000000000 --- a/src/Umbraco.Core/Models/MacroPropertyCollection.cs +++ /dev/null @@ -1,66 +0,0 @@ -using Umbraco.Cms.Core.Collections; -using Umbraco.Extensions; - -namespace Umbraco.Cms.Core.Models; - -/// -/// A macro's property collection -/// -public class MacroPropertyCollection : ObservableDictionary, IDeepCloneable -{ - public MacroPropertyCollection() - : base(property => property.Alias) - { - } - - public object DeepClone() - { - var clone = new MacroPropertyCollection(); - foreach (IMacroProperty item in this) - { - clone.Add((IMacroProperty)item.DeepClone()); - } - - return clone; - } - - /// - /// Used to update an existing macro property - /// - /// - /// - /// - /// - /// The existing property alias - /// - /// - public void UpdateProperty(string currentAlias, string? name = null, int? sortOrder = null, string? editorAlias = null, string? newAlias = null) - { - IMacroProperty prop = this[currentAlias]; - if (prop == null) - { - throw new InvalidOperationException("No property exists with alias " + currentAlias); - } - - if (name.IsNullOrWhiteSpace() == false) - { - prop.Name = name; - } - - if (sortOrder.HasValue) - { - prop.SortOrder = sortOrder.Value; - } - - if (name.IsNullOrWhiteSpace() == false && editorAlias is not null) - { - prop.EditorAlias = editorAlias; - } - - if (newAlias.IsNullOrWhiteSpace() == false && currentAlias != newAlias && newAlias is not null) - { - prop.Alias = newAlias; - ChangeKey(currentAlias, newAlias); - } - } -} diff --git a/src/Umbraco.Core/Models/Packaging/CompiledPackage.cs b/src/Umbraco.Core/Models/Packaging/CompiledPackage.cs index 6119d2cea1..eb6aa1c060 100644 --- a/src/Umbraco.Core/Models/Packaging/CompiledPackage.cs +++ b/src/Umbraco.Core/Models/Packaging/CompiledPackage.cs @@ -13,10 +13,6 @@ public class CompiledPackage public InstallWarnings Warnings { get; set; } = new(); - public IEnumerable Macros { get; set; } = null!; // TODO: make strongly typed - - public IEnumerable MacroPartialViews { get; set; } = null!; // TODO: make strongly typed - public IEnumerable Templates { get; set; } = null!; // TODO: make strongly typed public IEnumerable Stylesheets { get; set; } = null!; // TODO: make strongly typed diff --git a/src/Umbraco.Core/Models/Packaging/InstallWarnings.cs b/src/Umbraco.Core/Models/Packaging/InstallWarnings.cs index d1154f1b30..545e009cb2 100644 --- a/src/Umbraco.Core/Models/Packaging/InstallWarnings.cs +++ b/src/Umbraco.Core/Models/Packaging/InstallWarnings.cs @@ -3,8 +3,6 @@ namespace Umbraco.Cms.Core.Models.Packaging; public class InstallWarnings { // TODO: Shouldn't we detect other conflicting entities too ? - public IEnumerable? ConflictingMacros { get; set; } = Enumerable.Empty(); - public IEnumerable? ConflictingTemplates { get; set; } = Enumerable.Empty(); public IEnumerable? ConflictingStylesheets { get; set; } = Enumerable.Empty(); diff --git a/src/Umbraco.Core/Models/PartialView.cs b/src/Umbraco.Core/Models/PartialView.cs index 2900674570..07e2e1750a 100644 --- a/src/Umbraco.Core/Models/PartialView.cs +++ b/src/Umbraco.Core/Models/PartialView.cs @@ -9,14 +9,13 @@ namespace Umbraco.Cms.Core.Models; [DataContract(IsReference = true)] public class PartialView : File, IPartialView { - public PartialView(PartialViewType viewType, string path) - : this(viewType, path, null) + public PartialView(string path) + : this(path, null) { } - public PartialView(PartialViewType viewType, string path, Func? getFileContent) - : base(path, getFileContent) => - ViewType = viewType; - - public PartialViewType ViewType { get; set; } + public PartialView(string path, Func? getFileContent) + : base(path, getFileContent) + { + } } diff --git a/src/Umbraco.Core/Models/PartialViewMacroModel.cs b/src/Umbraco.Core/Models/PartialViewMacroModel.cs deleted file mode 100644 index 0d999d5dd6..0000000000 --- a/src/Umbraco.Core/Models/PartialViewMacroModel.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Umbraco.Cms.Core.Models.PublishedContent; - -namespace Umbraco.Cms.Core.Models; - -/// -/// The model used when rendering Partial View Macros -/// -public class PartialViewMacroModel : IContentModel -{ - public PartialViewMacroModel( - IPublishedContent page, - int macroId, - string? macroAlias, - string? macroName, - IDictionary macroParams) - { - Content = page; - MacroParameters = macroParams; - MacroName = macroName; - MacroAlias = macroAlias; - MacroId = macroId; - } - - public string? MacroName { get; } - - public string? MacroAlias { get; } - - public int MacroId { get; } - - public IDictionary MacroParameters { get; } - - public IPublishedContent Content { get; } -} diff --git a/src/Umbraco.Core/Models/PartialViewMacroModelExtensions.cs b/src/Umbraco.Core/Models/PartialViewMacroModelExtensions.cs deleted file mode 100644 index ecbf22323b..0000000000 --- a/src/Umbraco.Core/Models/PartialViewMacroModelExtensions.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Umbraco.Cms.Core; -using Umbraco.Cms.Core.Models; - -namespace Umbraco.Extensions; - -/// -/// Extension methods for the PartialViewMacroModel object -/// -public static class PartialViewMacroModelExtensions -{ - /// - /// Attempt to get a Macro parameter from a PartialViewMacroModel and return a default value otherwise - /// - /// - /// - /// - /// Parameter value if available, the default value that was passed otherwise. - public static T? GetParameterValue(this PartialViewMacroModel partialViewMacroModel, string parameterAlias, T defaultValue) - { - if (partialViewMacroModel.MacroParameters.ContainsKey(parameterAlias) == false || - string.IsNullOrEmpty(partialViewMacroModel.MacroParameters[parameterAlias]?.ToString())) - { - return defaultValue; - } - - Attempt attempt = partialViewMacroModel.MacroParameters[parameterAlias].TryConvertTo(typeof(T)); - - return attempt.Success ? (T?)attempt.Result : defaultValue; - } - - /// - /// Attempt to get a Macro parameter from a PartialViewMacroModel - /// - /// - /// - /// Parameter value if available, the default value for the type otherwise. - public static T? GetParameterValue(this PartialViewMacroModel partialViewMacroModel, string parameterAlias) => - partialViewMacroModel.GetParameterValue(parameterAlias, default(T)); -} diff --git a/src/Umbraco.Core/Models/PartialViewType.cs b/src/Umbraco.Core/Models/PartialViewType.cs deleted file mode 100644 index 65499be9a2..0000000000 --- a/src/Umbraco.Core/Models/PartialViewType.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Umbraco.Cms.Core.Models; - -public enum PartialViewType : byte -{ - Unknown = 0, // default - PartialView = 1, - PartialViewMacro = 2, -} diff --git a/src/Umbraco.Core/Notifications/MacroCacheRefresherNotification.cs b/src/Umbraco.Core/Notifications/MacroCacheRefresherNotification.cs deleted file mode 100644 index 4d88155074..0000000000 --- a/src/Umbraco.Core/Notifications/MacroCacheRefresherNotification.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Umbraco.Cms.Core.Sync; - -namespace Umbraco.Cms.Core.Notifications; - -public class MacroCacheRefresherNotification : CacheRefresherNotification -{ - public MacroCacheRefresherNotification(object messageObject, MessageType messageType) - : base(messageObject, messageType) - { - } -} diff --git a/src/Umbraco.Core/Notifications/MacroDeletedNotification.cs b/src/Umbraco.Core/Notifications/MacroDeletedNotification.cs deleted file mode 100644 index b42779415a..0000000000 --- a/src/Umbraco.Core/Notifications/MacroDeletedNotification.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Umbraco.Cms.Core.Events; -using Umbraco.Cms.Core.Models; - -namespace Umbraco.Cms.Core.Notifications; - -public class MacroDeletedNotification : DeletedNotification -{ - public MacroDeletedNotification(IMacro target, EventMessages messages) - : base(target, messages) - { - } -} diff --git a/src/Umbraco.Core/Notifications/MacroDeletingNotification.cs b/src/Umbraco.Core/Notifications/MacroDeletingNotification.cs deleted file mode 100644 index 8d262cb8aa..0000000000 --- a/src/Umbraco.Core/Notifications/MacroDeletingNotification.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Umbraco.Cms.Core.Events; -using Umbraco.Cms.Core.Models; - -namespace Umbraco.Cms.Core.Notifications; - -public class MacroDeletingNotification : DeletingNotification -{ - public MacroDeletingNotification(IMacro target, EventMessages messages) - : base(target, messages) - { - } - - public MacroDeletingNotification(IEnumerable target, EventMessages messages) - : base(target, messages) - { - } -} diff --git a/src/Umbraco.Core/Notifications/MacroSavedNotification.cs b/src/Umbraco.Core/Notifications/MacroSavedNotification.cs deleted file mode 100644 index 145ac6eb3d..0000000000 --- a/src/Umbraco.Core/Notifications/MacroSavedNotification.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Umbraco.Cms.Core.Events; -using Umbraco.Cms.Core.Models; - -namespace Umbraco.Cms.Core.Notifications; - -public class MacroSavedNotification : SavedNotification -{ - public MacroSavedNotification(IMacro target, EventMessages messages) - : base(target, messages) - { - } - - public MacroSavedNotification(IEnumerable target, EventMessages messages) - : base(target, messages) - { - } -} diff --git a/src/Umbraco.Core/Notifications/MacroSavingNotification.cs b/src/Umbraco.Core/Notifications/MacroSavingNotification.cs deleted file mode 100644 index 5786b76d81..0000000000 --- a/src/Umbraco.Core/Notifications/MacroSavingNotification.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Umbraco.Cms.Core.Events; -using Umbraco.Cms.Core.Models; - -namespace Umbraco.Cms.Core.Notifications; - -public class MacroSavingNotification : SavingNotification -{ - public MacroSavingNotification(IMacro target, EventMessages messages) - : base(target, messages) - { - } - - public MacroSavingNotification(IEnumerable target, EventMessages messages) - : base(target, messages) - { - } -} diff --git a/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs b/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs index fdb76f4bc2..f1ff955557 100644 --- a/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs +++ b/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs @@ -48,8 +48,6 @@ public class CompiledPackageXmlParser // this value is irrelevant during install. PackageFile = null, Name = package.Element("name")?.Value ?? string.Empty, - Macros = xml.Root.Element("Macros")?.Elements("macro") ?? Enumerable.Empty(), - MacroPartialViews = xml.Root.Element("MacroPartialViews")?.Elements("View") ?? Enumerable.Empty(), PartialViews = xml.Root.Element("PartialViews")?.Elements("View") ?? Enumerable.Empty(), Templates = xml.Root.Element("Templates")?.Elements("Template") ?? Enumerable.Empty(), Stylesheets = xml.Root.Element("Stylesheets")?.Elements("Stylesheet") ?? Enumerable.Empty(), @@ -76,7 +74,6 @@ public class CompiledPackageXmlParser { var installWarnings = new InstallWarnings { - ConflictingMacros = _conflictingPackageData.FindConflictingMacros(package.Macros), ConflictingTemplates = _conflictingPackageData.FindConflictingTemplates(package.Templates), ConflictingStylesheets = _conflictingPackageData.FindConflictingStylesheets(package.Stylesheets), }; diff --git a/src/Umbraco.Core/Packaging/ConflictingPackageData.cs b/src/Umbraco.Core/Packaging/ConflictingPackageData.cs index d71eada618..c1b16d7bf3 100644 --- a/src/Umbraco.Core/Packaging/ConflictingPackageData.cs +++ b/src/Umbraco.Core/Packaging/ConflictingPackageData.cs @@ -8,13 +8,9 @@ namespace Umbraco.Cms.Core.Packaging; public class ConflictingPackageData { private readonly IFileService _fileService; - private readonly IMacroService _macroService; - public ConflictingPackageData(IMacroService macroService, IFileService fileService) - { - _fileService = fileService ?? throw new ArgumentNullException(nameof(fileService)); - _macroService = macroService ?? throw new ArgumentNullException(nameof(macroService)); - } + public ConflictingPackageData(IFileService fileService) + => _fileService = fileService ?? throw new ArgumentNullException(nameof(fileService)); public IEnumerable? FindConflictingStylesheets(IEnumerable? stylesheetNodes) => stylesheetNodes? @@ -43,18 +39,4 @@ public class ConflictingPackageData return _fileService.GetTemplate(xElement.Value); }) .WhereNotNull(); - - public IEnumerable? FindConflictingMacros(IEnumerable? macroNodes) => - macroNodes? - .Select(n => - { - XElement? xElement = n.Element("alias") ?? n.Element("Alias"); - if (xElement == null) - { - throw new FormatException("missing a \"alias\" element in alias element"); - } - - return _macroService.GetByAlias(xElement.Value); - }) - .Where(v => v != null); } diff --git a/src/Umbraco.Core/Packaging/InstallationSummary.cs b/src/Umbraco.Core/Packaging/InstallationSummary.cs index d72ede1494..6625057bb8 100644 --- a/src/Umbraco.Core/Packaging/InstallationSummary.cs +++ b/src/Umbraco.Core/Packaging/InstallationSummary.cs @@ -22,10 +22,6 @@ public class InstallationSummary public IEnumerable DictionaryItemsInstalled { get; set; } = Enumerable.Empty(); - public IEnumerable MacrosInstalled { get; set; } = Enumerable.Empty(); - - public IEnumerable MacroPartialViewsInstalled { get; set; } = Enumerable.Empty(); - public IEnumerable TemplatesInstalled { get; set; } = Enumerable.Empty(); public IEnumerable DocumentTypesInstalled { get; set; } = Enumerable.Empty(); @@ -74,14 +70,11 @@ public class InstallationSummary } } - WriteConflicts(Warnings?.ConflictingMacros, x => x?.Alias, "Conflicting macros found, they will be overwritten: "); WriteConflicts(Warnings?.ConflictingTemplates, x => x.Alias, "Conflicting templates found, they will be overwritten: "); WriteConflicts(Warnings?.ConflictingStylesheets, x => x?.Alias, "Conflicting stylesheets found, they will be overwritten: "); WriteCount("Data types installed: ", DataTypesInstalled); WriteCount("Languages installed: ", LanguagesInstalled); WriteCount("Dictionary items installed: ", DictionaryItemsInstalled); - WriteCount("Macros installed: ", MacrosInstalled); - WriteCount("Macro partial views installed: ", MacroPartialViewsInstalled); WriteCount("Templates installed: ", TemplatesInstalled); WriteCount("Document types installed: ", DocumentTypesInstalled); WriteCount("Media types installed: ", MediaTypesInstalled); diff --git a/src/Umbraco.Core/Packaging/PackageDefinition.cs b/src/Umbraco.Core/Packaging/PackageDefinition.cs index 7b0b5f5df4..23f85619cc 100644 --- a/src/Umbraco.Core/Packaging/PackageDefinition.cs +++ b/src/Umbraco.Core/Packaging/PackageDefinition.cs @@ -36,9 +36,6 @@ public class PackageDefinition [DataMember(Name = "contentNodeId")] public string? ContentNodeId { get; set; } - [DataMember(Name = "macros")] - public IList Macros { get; set; } = new List(); - [DataMember(Name = "languages")] public IList Languages { get; set; } = new List(); diff --git a/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs b/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs index 99a18dbcf9..8a60ae8427 100644 --- a/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs +++ b/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs @@ -30,10 +30,6 @@ public class PackageDefinitionXmlParser xml.Element("media")?.Elements("nodeUdi").Select(x => (GuidUdi)UdiParser.Parse(x.Value)).ToList() ?? EmptyGuidUdiList, MediaLoadChildNodes = xml.Element("media")?.AttributeValue("loadChildNodes") ?? false, - Macros = - xml.Element("macros")?.Value - .Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).ToList() ?? - EmptyStringList, Templates = xml.Element("templates")?.Value .Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).ToList() ?? @@ -92,7 +88,6 @@ public class PackageDefinitionXmlParser new XElement("partialViews", string.Join(",", def.PartialViews ?? Array.Empty())), new XElement("documentTypes", string.Join(",", def.DocumentTypes ?? Array.Empty())), new XElement("mediaTypes", string.Join(",", def.MediaTypes ?? Array.Empty())), - new XElement("macros", string.Join(",", def.Macros ?? Array.Empty())), new XElement("languages", string.Join(",", def.Languages ?? Array.Empty())), new XElement("dictionaryitems", string.Join(",", def.DictionaryItems ?? Array.Empty())), new XElement( diff --git a/src/Umbraco.Core/Packaging/PackagesRepository.cs b/src/Umbraco.Core/Packaging/PackagesRepository.cs index a130712c07..d8848c5a0d 100644 --- a/src/Umbraco.Core/Packaging/PackagesRepository.cs +++ b/src/Umbraco.Core/Packaging/PackagesRepository.cs @@ -28,7 +28,6 @@ public class PackagesRepository : ICreatedPackagesRepository private readonly FileSystems _fileSystems; private readonly IHostingEnvironment _hostingEnvironment; private readonly ILocalizationService _languageService; - private readonly IMacroService _macroService; private readonly MediaFileManager _mediaFileManager; private readonly IMediaService _mediaService; private readonly IMediaTypeService _mediaTypeService; @@ -45,7 +44,6 @@ public class PackagesRepository : ICreatedPackagesRepository /// /// /// - /// /// /// /// @@ -65,7 +63,6 @@ public class PackagesRepository : ICreatedPackagesRepository IContentTypeService contentTypeService, IDataTypeService dataTypeService, IFileService fileService, - IMacroService macroService, ILocalizationService languageService, IHostingEnvironment hostingEnvironment, IEntityXmlSerializer serializer, @@ -88,7 +85,6 @@ public class PackagesRepository : ICreatedPackagesRepository _contentTypeService = contentTypeService; _dataTypeService = dataTypeService; _fileService = fileService; - _macroService = macroService; _languageService = languageService; _serializer = serializer; _hostingEnvironment = hostingEnvironment; @@ -234,7 +230,6 @@ public class PackagesRepository : ICreatedPackagesRepository PackageStylesheets(definition, root); PackageStaticFiles(definition.Scripts, root, "Scripts", "Script", _fileSystems.ScriptsFileSystem); PackageStaticFiles(definition.PartialViews, root, "PartialViews", "View", _fileSystems.PartialViewsFileSystem); - PackageMacros(definition, root); PackageDictionaryItems(definition, root); PackageLanguages(definition, root); PackageDataTypes(definition, root); @@ -467,39 +462,6 @@ public class PackagesRepository : ICreatedPackagesRepository } } - private void PackageMacros(PackageDefinition definition, XContainer root) - { - var packagedMacros = new List(); - var macros = new XElement("Macros"); - foreach (var macroId in definition.Macros) - { - if (!int.TryParse(macroId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt)) - { - continue; - } - - XElement? macroXml = GetMacroXml(outInt, out IMacro? macro); - if (macroXml == null) - { - continue; - } - - macros.Add(macroXml); - if (macro is not null) - { - packagedMacros.Add(macro); - } - } - - root.Add(macros); - - // Get the partial views for macros and package those (exclude views outside of the default directory, e.g. App_Plugins\*\Views) - IEnumerable views = packagedMacros.Where(x => x.MacroSource is not null) - .Where(x => x.MacroSource!.StartsWith(Constants.SystemDirectories.MacroPartials)) - .Select(x => x.MacroSource![Constants.SystemDirectories.MacroPartials.Length..].Replace('/', '\\')); - PackageStaticFiles(views, root, "MacroPartialViews", "View", _fileSystems.MacroPartialsFileSystem); - } - private void PackageStylesheets(PackageDefinition definition, XContainer root) { var stylesheetsXml = new XElement("Stylesheets"); @@ -761,19 +723,6 @@ public class PackagesRepository : ICreatedPackagesRepository return mediaStreams; } - // TODO: Delete this - private XElement? GetMacroXml(int macroId, out IMacro? macro) - { - macro = _macroService.GetById(macroId); - if (macro == null) - { - return null; - } - - XElement xml = _serializer.Serialize(macro); - return xml; - } - /// /// Converts a umbraco stylesheet to a package xml node /// diff --git a/src/Umbraco.Core/Persistence/Constants-DatabaseSchema.cs b/src/Umbraco.Core/Persistence/Constants-DatabaseSchema.cs index 07d7fb520c..bd9ac9e601 100644 --- a/src/Umbraco.Core/Persistence/Constants-DatabaseSchema.cs +++ b/src/Umbraco.Core/Persistence/Constants-DatabaseSchema.cs @@ -66,9 +66,6 @@ public static partial class Constants public const string TwoFactorLogin = TableNamePrefix + "TwoFactorLogin"; public const string ExternalLoginToken = TableNamePrefix + "ExternalLoginToken"; - public const string Macro = /*TableNamePrefix*/ "cms" + "Macro"; - public const string MacroProperty = /*TableNamePrefix*/ "cms" + "MacroProperty"; - public const string Member = /*TableNamePrefix*/ "cms" + "Member"; public const string MemberPropertyType = /*TableNamePrefix*/ "cms" + "MemberType"; public const string Member2MemberGroup = /*TableNamePrefix*/ "cms" + "Member2MemberGroup"; diff --git a/src/Umbraco.Core/Persistence/Repositories/IMacroRepository.cs b/src/Umbraco.Core/Persistence/Repositories/IMacroRepository.cs deleted file mode 100644 index 136abec3c4..0000000000 --- a/src/Umbraco.Core/Persistence/Repositories/IMacroRepository.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Umbraco.Cms.Core.Models; - -namespace Umbraco.Cms.Core.Persistence.Repositories; - -public interface IMacroRepository : IReadWriteQueryRepository, IReadRepository -{ - IMacro? GetByAlias(string alias); - - IEnumerable GetAllByAlias(string[] aliases); - -} diff --git a/src/Umbraco.Core/Persistence/Repositories/IPartialViewMacroRepository.cs b/src/Umbraco.Core/Persistence/Repositories/IPartialViewMacroRepository.cs deleted file mode 100644 index ba6d24c2d8..0000000000 --- a/src/Umbraco.Core/Persistence/Repositories/IPartialViewMacroRepository.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Umbraco.Cms.Core.Persistence.Repositories; - -// this only exists to differentiate with IPartialViewRepository in IoC -// without resorting to constants, names, whatever - and IPartialViewRepository -// is implemented by PartialViewRepository and IPartialViewMacroRepository by -// PartialViewMacroRepository - just to inject the proper filesystem. -public interface IPartialViewMacroRepository : IPartialViewRepository -{ -} diff --git a/src/Umbraco.Core/PropertyEditors/MarkDownPropertyValueEditor.cs b/src/Umbraco.Core/PropertyEditors/MarkDownPropertyValueEditor.cs index 637a971d68..9b8d5cffad 100644 --- a/src/Umbraco.Core/PropertyEditors/MarkDownPropertyValueEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/MarkDownPropertyValueEditor.cs @@ -8,10 +8,6 @@ using Umbraco.Extensions; namespace Umbraco.Cms.Core.PropertyEditors; -/// -/// A custom value editor to ensure that macro syntax is parsed when being persisted and formatted correctly for -/// display in the editor -/// internal class MarkDownPropertyValueEditor : DataValueEditor { private readonly IMarkdownSanitizer _markdownSanitizer; diff --git a/src/Umbraco.Core/PropertyEditors/ValueConverters/SimpleTinyMceValueConverter.cs b/src/Umbraco.Core/PropertyEditors/ValueConverters/SimpleTinyMceValueConverter.cs index 6d9c40e75c..d10e42ee30 100644 --- a/src/Umbraco.Core/PropertyEditors/ValueConverters/SimpleTinyMceValueConverter.cs +++ b/src/Umbraco.Core/PropertyEditors/ValueConverters/SimpleTinyMceValueConverter.cs @@ -15,7 +15,7 @@ public class SimpleTinyMceValueConverter : PropertyValueConverterBase public override Type GetPropertyValueType(IPublishedPropertyType propertyType) => typeof(IHtmlEncodedString); - // PropertyCacheLevel.Content is ok here because that converter does not parse {locallink} nor executes macros + // PropertyCacheLevel.Content is ok here because that converter does not parse {locallink} public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType) => PropertyCacheLevel.Element; diff --git a/src/Umbraco.Core/Routing/ContentFinderByPageIdQuery.cs b/src/Umbraco.Core/Routing/ContentFinderByPageIdQuery.cs index 7721551777..04123767c1 100644 --- a/src/Umbraco.Core/Routing/ContentFinderByPageIdQuery.cs +++ b/src/Umbraco.Core/Routing/ContentFinderByPageIdQuery.cs @@ -7,10 +7,6 @@ namespace Umbraco.Cms.Core.Routing; /// /// This looks up a document by checking for the umbPageId of a request/query string /// -/// -/// This is used by library.RenderTemplate and also some of the macro rendering functionality like in -/// macroResultWrapper.aspx -/// public class ContentFinderByPageIdQuery : IContentFinder { private readonly IRequestAccessor _requestAccessor; diff --git a/src/Umbraco.Core/Runtime/EssentialDirectoryCreator.cs b/src/Umbraco.Core/Runtime/EssentialDirectoryCreator.cs index 8d7ec082be..08672c1164 100644 --- a/src/Umbraco.Core/Runtime/EssentialDirectoryCreator.cs +++ b/src/Umbraco.Core/Runtime/EssentialDirectoryCreator.cs @@ -28,6 +28,5 @@ public class EssentialDirectoryCreator : INotificationHandler - /// Exports a list of items to xml as an - /// - /// Macros to export - /// containing the xml representation of the IMacro objects - public XElement Serialize(IEnumerable macros) - { - var xml = new XElement("Macros"); - foreach (IMacro item in macros) - { - xml.Add(Serialize(item)); - } - - return xml; - } - - public XElement Serialize(IMacro macro) - { - var xml = new XElement("macro"); - xml.Add(new XElement("name", macro.Name)); - xml.Add(new XElement("key", macro.Key)); - xml.Add(new XElement("alias", macro.Alias)); - xml.Add(new XElement("macroSource", macro.MacroSource)); - xml.Add(new XElement("useInEditor", macro.UseInEditor.ToString())); - xml.Add(new XElement("dontRender", macro.DontRender.ToString())); - xml.Add(new XElement("refreshRate", macro.CacheDuration.ToString(CultureInfo.InvariantCulture))); - xml.Add(new XElement("cacheByMember", macro.CacheByMember.ToString())); - xml.Add(new XElement("cacheByPage", macro.CacheByPage.ToString())); - - var properties = new XElement("properties"); - foreach (IMacroProperty property in macro.Properties) - { - properties.Add(new XElement( - "property", - new XAttribute("key", property.Key), - new XAttribute("name", property.Name!), - new XAttribute("alias", property.Alias), - new XAttribute("sortOrder", property.SortOrder), - new XAttribute("propertyType", property.EditorAlias))); - } - - xml.Add(properties); - - return xml; - } - public XElement Serialize(IContentType contentType) { var info = new XElement( diff --git a/src/Umbraco.Core/Services/FileService.cs b/src/Umbraco.Core/Services/FileService.cs index 021deed4f5..e481c45df6 100644 --- a/src/Umbraco.Core/Services/FileService.cs +++ b/src/Umbraco.Core/Services/FileService.cs @@ -25,10 +25,8 @@ namespace Umbraco.Cms.Core.Services; public class FileService : RepositoryService, IFileService { private const string PartialViewHeader = "@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage"; - private const string PartialViewMacroHeader = "@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage"; private readonly IAuditRepository _auditRepository; private readonly IHostingEnvironment _hostingEnvironment; - private readonly IPartialViewMacroRepository _partialViewMacroRepository; private readonly IPartialViewRepository _partialViewRepository; private readonly IScriptRepository _scriptRepository; private readonly IStylesheetRepository _stylesheetRepository; @@ -45,7 +43,6 @@ public class FileService : RepositoryService, IFileService IScriptRepository scriptRepository, ITemplateRepository templateRepository, IPartialViewRepository partialViewRepository, - IPartialViewMacroRepository partialViewMacroRepository, IAuditRepository auditRepository, IShortStringHelper shortStringHelper, IOptions globalSettings, @@ -57,7 +54,6 @@ public class FileService : RepositoryService, IFileService stylesheetRepository, scriptRepository, partialViewRepository, - partialViewMacroRepository, auditRepository, hostingEnvironment, StaticServiceProvider.Instance.GetRequiredService(), @@ -76,7 +72,6 @@ public class FileService : RepositoryService, IFileService IStylesheetRepository stylesheetRepository, IScriptRepository scriptRepository, IPartialViewRepository partialViewRepository, - IPartialViewMacroRepository partialViewMacroRepository, IAuditRepository auditRepository, IHostingEnvironment hostingEnvironment, ITemplateService templateService, @@ -90,7 +85,6 @@ public class FileService : RepositoryService, IFileService _stylesheetRepository = stylesheetRepository; _scriptRepository = scriptRepository; _partialViewRepository = partialViewRepository; - _partialViewMacroRepository = partialViewMacroRepository; _auditRepository = auditRepository; _hostingEnvironment = hostingEnvironment; _templateService = templateService; @@ -589,26 +583,6 @@ public class FileService : RepositoryService, IFileService #region Partial Views - [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] - public IEnumerable GetPartialViewSnippetNames(params string[] filterNames) - { - var snippetProvider = - new EmbeddedFileProvider(GetType().Assembly, "Umbraco.Cms.Core.EmbeddedResources.Snippets"); - - var files = snippetProvider.GetDirectoryContents(string.Empty) - .Where(x => !x.IsDirectory && x.Name.EndsWith(".cshtml")) - .Select(x => Path.GetFileNameWithoutExtension(x.Name)) - .Except(filterNames, StringComparer.InvariantCultureIgnoreCase) - .ToArray(); - - // Ensure the ones that are called 'Empty' are at the top - var empty = files.Where(x => Path.GetFileName(x)?.InvariantStartsWith("Empty") ?? false) - .OrderBy(x => x?.Length) - .ToArray(); - - return empty.Union(files.Except(empty)).WhereNotNull(); - } - [Obsolete("Please use IPartialViewFolderService for partial view folder operations - will be removed in Umbraco 15")] public void DeletePartialViewFolder(string folderPath) { @@ -619,15 +593,6 @@ public class FileService : RepositoryService, IFileService } } - public void DeletePartialViewMacroFolder(string folderPath) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope()) - { - _partialViewMacroRepository.DeleteFolder(folderPath); - scope.Complete(); - } - } - [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] public IEnumerable GetPartialViews(params string[] names) { @@ -646,44 +611,9 @@ public class FileService : RepositoryService, IFileService } } - public IPartialView? GetPartialViewMacro(string path) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) - { - return _partialViewMacroRepository.Get(path); - } - } - [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] - public Attempt CreatePartialView(IPartialView partialView, string? snippetName = null, int? userId = Constants.Security.SuperUserId) => - CreatePartialViewMacro(partialView, PartialViewType.PartialView, snippetName, userId); - - public Attempt CreatePartialViewMacro(IPartialView partialView, string? snippetName = null, int? userId = Constants.Security.SuperUserId) => - CreatePartialViewMacro(partialView, PartialViewType.PartialViewMacro, snippetName, userId); - - [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] - public bool DeletePartialView(string path, int? userId = null) => - DeletePartialViewMacro(path, PartialViewType.PartialView, userId); - - private Attempt CreatePartialViewMacro( - IPartialView partialView, - PartialViewType partialViewType, - string? snippetName = null, - int? userId = Constants.Security.SuperUserId) + public Attempt CreatePartialView(IPartialView partialView, string? snippetName = null, int? userId = Constants.Security.SuperUserId) { - string partialViewHeader; - switch (partialViewType) - { - case PartialViewType.PartialView: - partialViewHeader = PartialViewHeader; - break; - case PartialViewType.PartialViewMacro: - partialViewHeader = PartialViewMacroHeader; - break; - default: - throw new ArgumentOutOfRangeException(nameof(partialViewType)); - } - string? partialViewContent = null; if (snippetName.IsNullOrWhiteSpace() == false) { @@ -702,12 +632,9 @@ public class FileService : RepositoryService, IFileService snippetContent = StripPartialViewHeader(snippetContent); // Update Model.Content. to be Model. when used as PartialView - if (partialViewType == PartialViewType.PartialView) - { - snippetContent = snippetContent.Replace("Model.Content.", "Model."); - } + snippetContent = snippetContent.Replace("Model.Content.", "Model."); - partialViewContent = $"{partialViewHeader}{Environment.NewLine}{snippetContent}"; + partialViewContent = $"{PartialViewHeader}{Environment.NewLine}{snippetContent}"; } } @@ -721,18 +648,17 @@ public class FileService : RepositoryService, IFileService return Attempt.Fail(); } - IPartialViewRepository repository = GetPartialViewRepository(partialViewType); if (partialViewContent != null) { partialView.Content = partialViewContent; } - repository.Save(partialView); + _partialViewRepository.Save(partialView); scope.Notifications.Publish( new PartialViewCreatedNotification(partialView, eventMessages).WithStateFrom(creatingNotification)); - Audit(AuditType.Save, userId!.Value, -1, partialViewType.ToString()); + Audit(AuditType.Save, userId!.Value, -1, Constants.UdiEntityType.PartialView); scope.Complete(); } @@ -740,19 +666,38 @@ public class FileService : RepositoryService, IFileService return Attempt.Succeed(partialView); } - public bool DeletePartialViewMacro(string path, int? userId = null) => - DeletePartialViewMacro(path, PartialViewType.PartialViewMacro, userId); - [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] - public Attempt SavePartialView(IPartialView partialView, int? userId = null) => - SavePartialView(partialView, PartialViewType.PartialView, userId); - - private bool DeletePartialViewMacro(string path, PartialViewType partialViewType, int? userId = null) + public Attempt SavePartialView(IPartialView partialView, int? userId = null) { using (ICoreScope scope = ScopeProvider.CreateCoreScope()) { - IPartialViewRepository repository = GetPartialViewRepository(partialViewType); - IPartialView? partialView = repository.Get(path); + EventMessages eventMessages = EventMessagesFactory.Get(); + var savingNotification = new PartialViewSavingNotification(partialView, eventMessages); + if (scope.Notifications.PublishCancelable(savingNotification)) + { + scope.Complete(); + return Attempt.Fail(); + } + + userId ??= Constants.Security.SuperUserId; + _partialViewRepository.Save(partialView); + + Audit(AuditType.Save, userId.Value, -1, Constants.UdiEntityType.PartialView); + scope.Notifications.Publish( + new PartialViewSavedNotification(partialView, eventMessages).WithStateFrom(savingNotification)); + + scope.Complete(); + } + + return Attempt.Succeed(partialView); + } + + [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] + public bool DeletePartialView(string path, int? userId = null) + { + using (ICoreScope scope = ScopeProvider.CreateCoreScope()) + { + IPartialView? partialView = _partialViewRepository.Get(path); if (partialView == null) { scope.Complete(); @@ -768,10 +713,10 @@ public class FileService : RepositoryService, IFileService } userId ??= Constants.Security.SuperUserId; - repository.Delete(partialView); + _partialViewRepository.Delete(partialView); scope.Notifications.Publish( new PartialViewDeletedNotification(partialView, eventMessages).WithStateFrom(deletingNotification)); - Audit(AuditType.Delete, userId.Value, -1, partialViewType.ToString()); + Audit(AuditType.Delete, userId.Value, -1, Constants.UdiEntityType.PartialView); scope.Complete(); } @@ -779,9 +724,6 @@ public class FileService : RepositoryService, IFileService return true; } - public Attempt SavePartialViewMacro(IPartialView partialView, int? userId = null) => - SavePartialView(partialView, PartialViewType.PartialViewMacro, userId); - [Obsolete("Please use IPartialViewFolderService for partial view folder operations - will be removed in Umbraco 15")] public void CreatePartialViewFolder(string folderPath) { @@ -798,33 +740,6 @@ public class FileService : RepositoryService, IFileService return headerMatch.Replace(contents, string.Empty); } - [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] - private Attempt SavePartialView(IPartialView partialView, PartialViewType partialViewType, int? userId = null) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope()) - { - EventMessages eventMessages = EventMessagesFactory.Get(); - var savingNotification = new PartialViewSavingNotification(partialView, eventMessages); - if (scope.Notifications.PublishCancelable(savingNotification)) - { - scope.Complete(); - return Attempt.Fail(); - } - - userId ??= Constants.Security.SuperUserId; - IPartialViewRepository repository = GetPartialViewRepository(partialViewType); - repository.Save(partialView); - - Audit(AuditType.Save, userId.Value, -1, partialViewType.ToString()); - scope.Notifications.Publish( - new PartialViewSavedNotification(partialView, eventMessages).WithStateFrom(savingNotification)); - - scope.Complete(); - } - - return Attempt.Succeed(partialView); - } - internal Attempt TryGetSnippetPath(string? fileName) { if (fileName?.EndsWith(".cshtml") == false) @@ -840,15 +755,6 @@ public class FileService : RepositoryService, IFileService : Attempt.Fail(); } - public void CreatePartialViewMacroFolder(string folderPath) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope()) - { - _partialViewMacroRepository.AddFolder(folderPath); - scope.Complete(); - } - } - /// [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] public Stream GetPartialViewFileContentStream(string filepath) @@ -859,19 +765,6 @@ public class FileService : RepositoryService, IFileService } } - private IPartialViewRepository GetPartialViewRepository(PartialViewType partialViewType) - { - switch (partialViewType) - { - case PartialViewType.PartialView: - return _partialViewRepository; - case PartialViewType.PartialViewMacro: - return _partialViewMacroRepository; - default: - throw new ArgumentOutOfRangeException(nameof(partialViewType)); - } - } - /// [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] public void SetPartialViewFileContent(string filepath, Stream content) @@ -893,64 +786,17 @@ public class FileService : RepositoryService, IFileService } } - /// - public Stream GetPartialViewMacroFileContentStream(string filepath) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) - { - return _partialViewMacroRepository.GetFileContentStream(filepath); - } - } - - /// - public void SetPartialViewMacroFileContent(string filepath, Stream content) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope()) - { - _partialViewMacroRepository.SetFileContent(filepath, content); - scope.Complete(); - } - } - - /// - public long GetPartialViewMacroFileSize(string filepath) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) - { - return _partialViewMacroRepository.GetFileSize(filepath); - } - } - #endregion #region Snippets - public string GetPartialViewSnippetContent(string snippetName) => - GetPartialViewMacroSnippetContent(snippetName, PartialViewType.PartialView); - - public string GetPartialViewMacroSnippetContent(string snippetName) => - GetPartialViewMacroSnippetContent(snippetName, PartialViewType.PartialViewMacro); - - private string GetPartialViewMacroSnippetContent(string snippetName, PartialViewType partialViewType) + public string GetPartialViewSnippetContent(string snippetName) { if (snippetName.IsNullOrWhiteSpace()) { throw new ArgumentNullException(nameof(snippetName)); } - string partialViewHeader; - switch (partialViewType) - { - case PartialViewType.PartialView: - partialViewHeader = PartialViewHeader; - break; - case PartialViewType.PartialViewMacro: - partialViewHeader = PartialViewMacroHeader; - break; - default: - throw new ArgumentOutOfRangeException(nameof(partialViewType)); - } - var snippetProvider = new EmbeddedFileProvider(GetType().Assembly, "Umbraco.Cms.Core.EmbeddedResources.Snippets"); @@ -971,14 +817,11 @@ public class FileService : RepositoryService, IFileService snippetContent = StripPartialViewHeader(snippetContent); // Update Model.Content to be Model when used as PartialView - if (partialViewType == PartialViewType.PartialView) - { - snippetContent = snippetContent - .Replace("Model.Content.", "Model.") - .Replace("(Model.Content)", "(Model)"); - } + snippetContent = snippetContent + .Replace("Model.Content.", "Model.") + .Replace("(Model.Content)", "(Model)"); - var content = $"{partialViewHeader}{Environment.NewLine}{snippetContent}"; + var content = $"{PartialViewHeader}{Environment.NewLine}{snippetContent}"; return content; } } diff --git a/src/Umbraco.Core/Services/IEntityXmlSerializer.cs b/src/Umbraco.Core/Services/IEntityXmlSerializer.cs index 5ada7ab5b6..172f710a21 100644 --- a/src/Umbraco.Core/Services/IEntityXmlSerializer.cs +++ b/src/Umbraco.Core/Services/IEntityXmlSerializer.cs @@ -77,14 +77,5 @@ public interface IEntityXmlSerializer XElement Serialize(IMediaType mediaType); - /// - /// Exports a list of items to xml as an - /// - /// Macros to export - /// containing the xml representation of the IMacro objects - XElement Serialize(IEnumerable macros); - - XElement Serialize(IMacro macro); - XElement Serialize(IContentType contentType); } diff --git a/src/Umbraco.Core/Services/IFileService.cs b/src/Umbraco.Core/Services/IFileService.cs index 8bf4e0a605..2c0829fa52 100644 --- a/src/Umbraco.Core/Services/IFileService.cs +++ b/src/Umbraco.Core/Services/IFileService.cs @@ -8,19 +8,12 @@ namespace Umbraco.Cms.Core.Services; /// public interface IFileService : IService { - [Obsolete("Please use SnippetCollection.GetPartialViewSnippetNames() or SnippetCollection.GetPartialViewMacroSnippetNames() instead. Scheduled for removal in V12.")] - IEnumerable GetPartialViewSnippetNames(params string[] filterNames); - [Obsolete("Please use IPartialViewFolderService for partial view folder operations - will be removed in Umbraco 15")] void CreatePartialViewFolder(string folderPath); - void CreatePartialViewMacroFolder(string folderPath); - [Obsolete("Please use IPartialViewFolderService for partial view folder operations - will be removed in Umbraco 15")] void DeletePartialViewFolder(string folderPath); - void DeletePartialViewMacroFolder(string folderPath); - /// /// Gets a list of all objects /// @@ -31,23 +24,15 @@ public interface IFileService : IService [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] IPartialView? GetPartialView(string path); - IPartialView? GetPartialViewMacro(string path); - [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] Attempt CreatePartialView(IPartialView partialView, string? snippetName = null, int? userId = Constants.Security.SuperUserId); - Attempt CreatePartialViewMacro(IPartialView partialView, string? snippetName = null, int? userId = Constants.Security.SuperUserId); - [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] bool DeletePartialView(string path, int? userId = null); - bool DeletePartialViewMacro(string path, int? userId = null); - [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] Attempt SavePartialView(IPartialView partialView, int? userId = null); - Attempt SavePartialViewMacro(IPartialView partialView, int? userId = null); - /// /// Gets the content of a partial view as a stream. /// @@ -72,27 +57,6 @@ public interface IFileService : IService [Obsolete("Please use IPartialViewService for partial view operations - will be removed in Umbraco 15")] long GetPartialViewFileSize(string filepath); - /// - /// Gets the content of a macro partial view as a stream. - /// - /// The filesystem path to the macro partial view. - /// The content of the macro partial view. - Stream GetPartialViewMacroFileContentStream(string filepath); - - /// - /// Sets the content of a macro partial view. - /// - /// The filesystem path to the macro partial view. - /// The content of the macro partial view. - void SetPartialViewMacroFileContent(string filepath, Stream content); - - /// - /// Gets the size of a macro partial view. - /// - /// The filesystem path to the macro partial view. - /// The size of the macro partial view. - long GetPartialViewMacroFileSize(string filepath); - /// /// Gets a list of all objects /// @@ -345,14 +309,6 @@ public interface IFileService : IService [Obsolete("Please use ITemplateService for template operations - will be removed in Umbraco 15")] long GetTemplateFileSize(string filepath); - /// - /// Gets the content of a macro partial view snippet as a string - /// - /// The name of the snippet - /// - [Obsolete("Please use SnippetCollection.GetPartialViewMacroSnippetContent instead. Scheduled for removal in V12.")] - string GetPartialViewMacroSnippetContent(string snippetName); - /// /// Gets the content of a partial view snippet as a string. /// diff --git a/src/Umbraco.Core/Services/IMacroService.cs b/src/Umbraco.Core/Services/IMacroService.cs deleted file mode 100644 index ef99248727..0000000000 --- a/src/Umbraco.Core/Services/IMacroService.cs +++ /dev/null @@ -1,60 +0,0 @@ -using Umbraco.Cms.Core.Models; - -namespace Umbraco.Cms.Core.Services; - -/// -/// Defines the MacroService, which is an easy access to operations involving -/// -public interface IMacroService : IService -{ - /// - /// Gets an object by its alias - /// - /// Alias to retrieve an for - /// An object - IMacro? GetByAlias(string alias); - - IEnumerable GetAll(); - - IEnumerable GetAll(params int[] ids); - - IEnumerable GetAll(params Guid[] ids); - - IMacro? GetById(int id); - - IMacro? GetById(Guid id); - - /// - /// Deletes an - /// - /// to delete - /// Optional id of the user deleting the macro - void Delete(IMacro macro, int userId = Constants.Security.SuperUserId); - - /// - /// Saves an - /// - /// to save - /// Optional id of the user saving the macro - void Save(IMacro macro, int userId = Constants.Security.SuperUserId); - - ///// - ///// Gets a list all available plugins - ///// - ///// An enumerable list of objects - // IEnumerable GetMacroPropertyTypes(); - - ///// - ///// Gets an by its alias - ///// - ///// Alias to retrieve an for - ///// An object - //IMacroPropertyType GetMacroPropertyTypeByAlias(string alias); - - /// - /// Gets a list of available objects by alias. - /// - /// Optional array of aliases to limit the results - /// An enumerable list of objects - IEnumerable GetAll(params string[] aliases); -} diff --git a/src/Umbraco.Core/Services/MacroService.cs b/src/Umbraco.Core/Services/MacroService.cs deleted file mode 100644 index be07d1ef02..0000000000 --- a/src/Umbraco.Core/Services/MacroService.cs +++ /dev/null @@ -1,176 +0,0 @@ -using Microsoft.Extensions.Logging; -using Umbraco.Cms.Core.Events; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Notifications; -using Umbraco.Cms.Core.Persistence.Repositories; -using Umbraco.Cms.Core.Scoping; - -namespace Umbraco.Cms.Core.Services; - -/// -/// Represents the Macro Service, which is an easy access to operations involving -/// -internal class MacroService : RepositoryService, IMacroService -{ - private readonly IAuditRepository _auditRepository; - private readonly IMacroRepository _macroRepository; - - public MacroService( - ICoreScopeProvider provider, - ILoggerFactory loggerFactory, - IEventMessagesFactory eventMessagesFactory, - IMacroRepository macroRepository, - IAuditRepository auditRepository) - : base(provider, loggerFactory, eventMessagesFactory) - { - _macroRepository = macroRepository; - _auditRepository = auditRepository; - } - - /// - /// Gets an object by its alias - /// - /// Alias to retrieve an for - /// An object - public IMacro? GetByAlias(string alias) - { - if (_macroRepository is not IMacroRepository macroWithAliasRepository) - { - return GetAll().FirstOrDefault(x => x.Alias == alias); - } - - using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) - { - return macroWithAliasRepository.GetByAlias(alias); - } - } - - public IEnumerable GetAll() => GetAll(new int[0]); - - public IEnumerable GetAll(params int[] ids) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) - { - return _macroRepository.GetMany(ids); - } - } - - public IEnumerable GetAll(params Guid[] ids) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) - { - return _macroRepository.GetMany(ids); - } - } - - public IEnumerable GetAll(params string[] aliases) - { - if (_macroRepository is not IMacroRepository macroWithAliasRepository) - { - var hashset = new HashSet(aliases); - return GetAll().Where(x => hashset.Contains(x.Alias)); - } - - using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) - { - return macroWithAliasRepository.GetAllByAlias(aliases); - } - } - - public IMacro? GetById(int id) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) - { - return _macroRepository.Get(id); - } - } - - public IMacro? GetById(Guid id) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true)) - { - return _macroRepository.Get(id); - } - } - - /// - /// Deletes an - /// - /// to delete - /// Optional id of the user deleting the macro - public void Delete(IMacro macro, int userId = Constants.Security.SuperUserId) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope()) - { - EventMessages eventMessages = EventMessagesFactory.Get(); - var deletingNotification = new MacroDeletingNotification(macro, eventMessages); - if (scope.Notifications.PublishCancelable(deletingNotification)) - { - scope.Complete(); - return; - } - - _macroRepository.Delete(macro); - - scope.Notifications.Publish( - new MacroDeletedNotification(macro, eventMessages).WithStateFrom(deletingNotification)); - Audit(AuditType.Delete, userId, -1); - - scope.Complete(); - } - } - - /// - /// Saves an - /// - /// to save - /// Optional Id of the user deleting the macro - public void Save(IMacro macro, int userId = Constants.Security.SuperUserId) - { - using (ICoreScope scope = ScopeProvider.CreateCoreScope()) - { - EventMessages eventMessages = EventMessagesFactory.Get(); - var savingNotification = new MacroSavingNotification(macro, eventMessages); - - if (scope.Notifications.PublishCancelable(savingNotification)) - { - scope.Complete(); - return; - } - - if (string.IsNullOrWhiteSpace(macro.Name)) - { - throw new ArgumentException("Cannot save macro with empty name."); - } - - _macroRepository.Save(macro); - - scope.Notifications.Publish( - new MacroSavedNotification(macro, eventMessages).WithStateFrom(savingNotification)); - Audit(AuditType.Save, userId, -1); - - scope.Complete(); - } - } - - ///// - ///// Gets a list all available plugins - ///// - ///// An enumerable list of objects - // public IEnumerable GetMacroPropertyTypes() - // { - // return MacroPropertyTypeResolver.Current.MacroPropertyTypes; - // } - - ///// - ///// Gets an by its alias - ///// - ///// Alias to retrieve an for - ///// An object - // public IMacroPropertyType GetMacroPropertyTypeByAlias(string alias) - // { - // return MacroPropertyTypeResolver.Current.MacroPropertyTypes.FirstOrDefault(x => x.Alias == alias); - // } - private void Audit(AuditType type, int userId, int objectId) => - _auditRepository.Save(new AuditItem(objectId, type, userId, "Macro")); -} diff --git a/src/Umbraco.Core/Services/PartialViewService.cs b/src/Umbraco.Core/Services/PartialViewService.cs index ba636755a4..d4bfb5dc6d 100644 --- a/src/Umbraco.Core/Services/PartialViewService.cs +++ b/src/Umbraco.Core/Services/PartialViewService.cs @@ -59,7 +59,7 @@ public class PartialViewService : FileServiceOperationBase new(target, messages); protected override IPartialView CreateEntity(string path, string? content) - => new PartialView(PartialViewType.PartialView, path) { Content = content }; + => new PartialView(path) { Content = content }; /// public async Task> GetSnippetsAsync(int skip, int take) diff --git a/src/Umbraco.Core/Services/ServiceContext.cs b/src/Umbraco.Core/Services/ServiceContext.cs index b28e0aaaee..876fad46f4 100644 --- a/src/Umbraco.Core/Services/ServiceContext.cs +++ b/src/Umbraco.Core/Services/ServiceContext.cs @@ -18,7 +18,6 @@ public class ServiceContext private readonly Lazy? _keyValueService; private readonly Lazy? _localizationService; private readonly Lazy? _localizedTextService; - private readonly Lazy? _macroService; private readonly Lazy? _mediaService; private readonly Lazy? _mediaTypeService; private readonly Lazy? _memberGroupService; @@ -56,7 +55,6 @@ public class ServiceContext Lazy? serverRegistrationService, Lazy? entityService, Lazy? relationService, - Lazy? macroService, Lazy? memberTypeService, Lazy? memberGroupService, Lazy? notificationService, @@ -85,7 +83,6 @@ public class ServiceContext _serverRegistrationService = serverRegistrationService; _entityService = entityService; _relationService = relationService; - _macroService = macroService; _memberTypeService = memberTypeService; _memberGroupService = memberGroupService; _notificationService = notificationService; @@ -132,11 +129,6 @@ public class ServiceContext /// public ITagService? TagService => _tagService?.Value; - /// - /// Gets the - /// - public IMacroService? MacroService => _macroService?.Value; - /// /// Gets the /// @@ -263,7 +255,6 @@ public class ServiceContext ILocalizedTextService? localizedTextService = null, IAuditService? auditService = null, IDomainService? domainService = null, - IMacroService? macroService = null, IPublicAccessService? publicAccessService = null, IExternalLoginWithKeyService? externalLoginService = null, IServerRegistrationService? serverRegistrationService = null, @@ -297,7 +288,6 @@ public class ServiceContext Lazy(serverRegistrationService), Lazy(entityService), Lazy(relationService), - Lazy(macroService), Lazy(memberTypeService), Lazy(memberGroupService), Lazy(notificationService), diff --git a/src/Umbraco.Core/Snippets/PartialViewSnippetCollectionBuilder.cs b/src/Umbraco.Core/Snippets/PartialViewSnippetCollectionBuilder.cs index 90f5551ea8..31f33cf6f2 100644 --- a/src/Umbraco.Core/Snippets/PartialViewSnippetCollectionBuilder.cs +++ b/src/Umbraco.Core/Snippets/PartialViewSnippetCollectionBuilder.cs @@ -18,15 +18,6 @@ public partial class PartialViewSnippetCollectionBuilder : LazyCollectionBuilder { var embeddedSnippets = new List(base.CreateItems(factory)); - // Ignore these - var filterNames = new List - { - "Gallery", - "ListChildPagesFromChangeableSource", - "ListChildPagesOrderedByProperty", - "ListImagesFromMediaFolder" - }; - var snippetProvider = new EmbeddedFileProvider(typeof(IAssemblyProvider).Assembly, "Umbraco.Cms.Core.EmbeddedResources.Snippets"); IEnumerable embeddedFiles = snippetProvider.GetDirectoryContents(string.Empty) .Where(x => !x.IsDirectory && x.Name.EndsWith(".cshtml")); @@ -35,11 +26,6 @@ public partial class PartialViewSnippetCollectionBuilder : LazyCollectionBuilder foreach (IFileInfo file in embeddedFiles) { var id = Path.GetFileNameWithoutExtension(file.Name); - if (filterNames.Contains(id)) - { - continue; - } - var name = id.SplitPascalCasing(shortStringHelper).ToFirstUpperInvariant(); using var stream = new StreamReader(file.CreateReadStream()); var content = CleanUpSnippetContent(stream.ReadToEnd().Trim()); diff --git a/src/Umbraco.Core/Templates/IUmbracoComponentRenderer.cs b/src/Umbraco.Core/Templates/IUmbracoComponentRenderer.cs index b94d575b9f..1ec380d9ca 100644 --- a/src/Umbraco.Core/Templates/IUmbracoComponentRenderer.cs +++ b/src/Umbraco.Core/Templates/IUmbracoComponentRenderer.cs @@ -1,4 +1,3 @@ -using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.Strings; namespace Umbraco.Cms.Core.Templates; @@ -14,40 +13,4 @@ public interface IUmbracoComponentRenderer /// The content id /// If not specified, will use the template assigned to the node Task RenderTemplateAsync(int contentId, int? altTemplateId = null); - - /// - /// Renders the macro with the specified alias. - /// - /// The content id - /// The alias. - Task RenderMacroAsync(int contentId, string alias); - - /// - /// Renders the macro with the specified alias, passing in the specified parameters. - /// - /// The content id - /// The alias. - /// The parameters. - Task RenderMacroAsync(int contentId, string alias, object parameters); - - /// - /// Renders the macro with the specified alias, passing in the specified parameters. - /// - /// The content id - /// The alias. - /// The parameters. - Task RenderMacroAsync(int contentId, string alias, IDictionary? parameters); - - /// - /// Renders the macro with the specified alias, passing in the specified parameters. - /// - /// An IPublishedContent to use for the context for the macro rendering - /// The alias. - /// The parameters. - /// A raw HTML string of the macro output - /// - /// Currently only used when the node is unpublished and unable to get the contentId item from the - /// content cache as its unpublished. This deals with taking in a preview/draft version of the content node - /// - Task RenderMacroForContent(IPublishedContent content, string alias, IDictionary? parameters); } diff --git a/src/Umbraco.Core/Templates/UmbracoComponentRenderer.cs b/src/Umbraco.Core/Templates/UmbracoComponentRenderer.cs index e419bd5be3..97599bcb43 100644 --- a/src/Umbraco.Core/Templates/UmbracoComponentRenderer.cs +++ b/src/Umbraco.Core/Templates/UmbracoComponentRenderer.cs @@ -1,9 +1,4 @@ -using System.Net; -using Umbraco.Cms.Core.Macros; -using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.Strings; -using Umbraco.Cms.Core.Web; -using Umbraco.Extensions; namespace Umbraco.Cms.Core.Templates; @@ -15,19 +10,13 @@ namespace Umbraco.Cms.Core.Templates; /// public class UmbracoComponentRenderer : IUmbracoComponentRenderer { - private readonly IMacroRenderer _macroRenderer; private readonly ITemplateRenderer _templateRenderer; - private readonly IUmbracoContextAccessor _umbracoContextAccessor; /// /// Initializes a new instance of the class. /// - public UmbracoComponentRenderer(IUmbracoContextAccessor umbracoContextAccessor, IMacroRenderer macroRenderer, ITemplateRenderer templateRenderer) - { - _umbracoContextAccessor = umbracoContextAccessor; - _macroRenderer = macroRenderer; - _templateRenderer = templateRenderer ?? throw new ArgumentNullException(nameof(templateRenderer)); - } + public UmbracoComponentRenderer(ITemplateRenderer templateRenderer) + => _templateRenderer = templateRenderer ?? throw new ArgumentNullException(nameof(templateRenderer)); /// public async Task RenderTemplateAsync(int contentId, int? altTemplateId = null) @@ -46,63 +35,4 @@ public class UmbracoComponentRenderer : IUmbracoComponentRenderer return new HtmlEncodedString(sw.ToString()); } } - - /// - public async Task RenderMacroAsync(int contentId, string alias) => - await RenderMacroAsync(contentId, alias, new { }); - - /// - public async Task RenderMacroAsync(int contentId, string alias, object parameters) => - await RenderMacroAsync(contentId, alias, parameters.ToDictionary()); - - /// - public async Task RenderMacroAsync(int contentId, string alias, IDictionary? parameters) - { - if (contentId == default) - { - throw new ArgumentException("Invalid content id " + contentId); - } - - IUmbracoContext umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); - IPublishedContent? content = umbracoContext.Content?.GetById(contentId); - - if (content == null) - { - throw new InvalidOperationException("Cannot render a macro, no content found by id " + contentId); - } - - return await RenderMacroAsync(content, alias, parameters); - } - - /// - public async Task RenderMacroForContent(IPublishedContent content, string alias, IDictionary? parameters) - { - if (content == null) - { - throw new InvalidOperationException("Cannot render a macro, IPublishedContent is null"); - } - - return await RenderMacroAsync(content, alias, parameters); - } - - /// - /// Renders the macro with the specified alias, passing in the specified parameters. - /// - private async Task RenderMacroAsync(IPublishedContent content, string alias, IDictionary? parameters) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - - // TODO: We are doing at ToLower here because for some insane reason the UpdateMacroModel method looks for a lower case match. the whole macro concept needs to be rewritten. - // NOTE: the value could have HTML encoded values, so we need to deal with that - var macroProps = parameters?.ToDictionary( - x => x.Key.ToLowerInvariant(), - i => i.Value is string ? WebUtility.HtmlDecode(i.Value.ToString()) : i.Value); - - var html = (await _macroRenderer.RenderAsync(alias, content, macroProps)).Text; - - return new HtmlEncodedString(html!); - } } diff --git a/src/Umbraco.Core/UdiParser.cs b/src/Umbraco.Core/UdiParser.cs index 40a676d659..c91c12b22b 100644 --- a/src/Umbraco.Core/UdiParser.cs +++ b/src/Umbraco.Core/UdiParser.cs @@ -207,7 +207,6 @@ public sealed class UdiParser { Constants.UdiEntityType.Media, UdiType.GuidUdi }, { Constants.UdiEntityType.Member, UdiType.GuidUdi }, { Constants.UdiEntityType.DictionaryItem, UdiType.GuidUdi }, - { Constants.UdiEntityType.Macro, UdiType.GuidUdi }, { Constants.UdiEntityType.Template, UdiType.GuidUdi }, { Constants.UdiEntityType.DocumentType, UdiType.GuidUdi }, { Constants.UdiEntityType.DocumentTypeContainer, UdiType.GuidUdi }, @@ -224,12 +223,10 @@ public sealed class UdiParser { Constants.UdiEntityType.FormsDataSource, UdiType.GuidUdi }, { Constants.UdiEntityType.AnyString, UdiType.StringUdi }, { Constants.UdiEntityType.Language, UdiType.StringUdi }, - { Constants.UdiEntityType.MacroScript, UdiType.StringUdi }, { Constants.UdiEntityType.MediaFile, UdiType.StringUdi }, { Constants.UdiEntityType.TemplateFile, UdiType.StringUdi }, { Constants.UdiEntityType.Script, UdiType.StringUdi }, { Constants.UdiEntityType.PartialView, UdiType.StringUdi }, - { Constants.UdiEntityType.PartialViewMacro, UdiType.StringUdi }, { Constants.UdiEntityType.Stylesheet, UdiType.StringUdi }, { Constants.UdiEntityType.Webhook, UdiType.GuidUdi }, }; diff --git a/src/Umbraco.Core/Xml/XPath/MacroNavigator.cs b/src/Umbraco.Core/Xml/XPath/MacroNavigator.cs deleted file mode 100644 index 3d706eed80..0000000000 --- a/src/Umbraco.Core/Xml/XPath/MacroNavigator.cs +++ /dev/null @@ -1,1082 +0,0 @@ -using System.Diagnostics; -using System.Xml; -using System.Xml.XPath; - -namespace Umbraco.Cms.Core.Xml.XPath -{ - /// - /// Provides a cursor model for navigating {macro /} as if it were XML. - /// - [Obsolete("The current implementation of XPath is suboptimal and will be removed entirely in a future version. Scheduled for removal in v14")] - public class MacroNavigator : XPathNavigator - { - private readonly XmlNameTable _nameTable; - private readonly MacroRoot _macro; - private State _state; - - #region Constructor - - /// - /// Initializes a new instance of the class with macro parameters. - /// - /// The macro parameters. - public MacroNavigator(IEnumerable parameters) - : this(new MacroRoot(parameters), new NameTable(), new State()) - { } - - /// - /// Initializes a new instance of the class with a macro node, - /// a name table and a state. - /// - /// The macro node. - /// The name table. - /// The state. - /// Privately used for cloning a navigator. - private MacroNavigator(MacroRoot macro, XmlNameTable nameTable, State state) - { - _macro = macro; - _nameTable = nameTable; - _state = state; - } - - #endregion - - #region Diagnostics - - // diagnostics code will not be compiled nor called into Release configuration. - // in Debug configuration, uncomment lines in Debug() to write to console or to log. - // - // much of this code is duplicated in each navigator due to conditional compilation - -#if DEBUG - private const string Tabs = " "; - private int _tabs; - private readonly int _uid = GetUid(); - private static int _uidg; - private static readonly object Uidl = new object(); - private static int GetUid() - { - lock (Uidl) - { - return _uidg++; - } - } -#endif - - [Conditional("DEBUG")] - private void DebugEnter(string name) - { -#if DEBUG - Debug(string.Empty); - DebugState(":"); - Debug(name); - _tabs = Math.Min(Tabs.Length, _tabs + 2); -#endif - } - - [Conditional("DEBUG")] - private void DebugCreate(MacroNavigator nav) - { -#if DEBUG - Debug("Create: [MacroNavigator::{0}]", nav._uid); -#endif - } - - [Conditional("DEBUG")] - private void DebugReturn() - { -#if DEBUG -// ReSharper disable IntroduceOptionalParameters.Local - DebugReturn("(void)"); -// ReSharper restore IntroduceOptionalParameters.Local -#endif - } - - [Conditional("DEBUG")] - private void DebugReturn(bool value) - { -#if DEBUG - DebugReturn(value ? "true" : "false"); -#endif - } - - [Conditional("DEBUG")] - private void DebugReturn(string format, params object[] args) - { -#if DEBUG - Debug("=> " + format, args); - if (_tabs > 0) - { - _tabs -= 2; - } -#endif - } - - [Conditional("DEBUG")] - private void DebugState(string s = " =>") - { -#if DEBUG - string position; - - switch (_state.Position) - { - case StatePosition.Macro: - position = "At macro."; - break; - case StatePosition.Parameter: - position = string.Format("At parameter '{0}'.", _macro.Parameters[_state.ParameterIndex].Name); - break; - case StatePosition.ParameterAttribute: - position = string.Format( - "At parameter attribute '{0}/{1}'.", - _macro.Parameters[_state.ParameterIndex].Name, - _macro.Parameters[_state.ParameterIndex].Attributes?[_state.ParameterAttributeIndex].Key); - break; - case StatePosition.ParameterNavigator: - position = string.Format( - "In parameter '{0}{1}' navigator.", - _macro.Parameters[_state.ParameterIndex].Name, - _macro.Parameters[_state.ParameterIndex].WrapNavigatorInNodes ? "/nodes" : string.Empty); - break; - case StatePosition.ParameterNodes: - position = string.Format( - "At parameter '{0}/nodes'.", - _macro.Parameters[_state.ParameterIndex].Name); - break; - case StatePosition.ParameterText: - position = string.Format( - "In parameter '{0}' text.", - _macro.Parameters[_state.ParameterIndex].Name); - break; - case StatePosition.Root: - position = "At root."; - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - Debug("State{0} {1}", s, position); -#endif - } - -#if DEBUG - private void Debug(string format, params object[] args) - { - // remove comments to write - - format = "[" + _uid.ToString("00000") + "] " + Tabs.Substring(0, _tabs) + format; -#pragma warning disable 168 - var msg = string.Format(format, args); // unused if not writing, hence #pragma -#pragma warning restore 168 - } -#endif - - #endregion - - #region Macro - - private class MacroRoot - { - public MacroRoot(IEnumerable parameters) - { - Parameters = parameters == null ? new MacroParameter[] {} : parameters.ToArray(); - } - - public MacroParameter[] Parameters { get; private set; } - } - - public class MacroParameter - { - // note: assuming we're not thinking about supporting - // XPathIterator in parameters - enough nonsense! - - public MacroParameter(string name, string value) - { - Name = name; - StringValue = value; - } - - public MacroParameter( - string name, - XPathNavigator navigator, - int maxNavigatorDepth = int.MaxValue, - bool wrapNavigatorInNodes = false, - IEnumerable>? attributes = null) - { - Name = name; - MaxNavigatorDepth = maxNavigatorDepth; - WrapNavigatorInNodes = wrapNavigatorInNodes; - if (attributes != null) - { - KeyValuePair[] a = attributes.ToArray(); - if (a.Length > 0) - { - Attributes = a; - } - } - - NavigatorValue = navigator; // should not be empty - } - - public string Name { get; private set; } - public string? StringValue { get; private set; } - public XPathNavigator? NavigatorValue { get; private set; } - public int MaxNavigatorDepth { get; private set; } - public bool WrapNavigatorInNodes { get; private set; } - public KeyValuePair[]? Attributes { get; private set; } - } - - #endregion - - /// - /// Creates a new XPathNavigator positioned at the same node as this XPathNavigator. - /// - /// A new XPathNavigator positioned at the same node as this XPathNavigator. - public override XPathNavigator Clone() - { - DebugEnter("Clone"); - var nav = new MacroNavigator(_macro, _nameTable, _state.Clone()); - DebugCreate(nav); - DebugReturn("[XPathNavigator]"); - return nav; - } - - /// - /// Gets a value indicating whether the current node is an empty element without an end element tag. - /// - public override bool IsEmptyElement - { - get - { - DebugEnter("IsEmptyElement"); - bool isEmpty; - - switch (_state.Position) - { - case StatePosition.Macro: - isEmpty = _macro.Parameters.Length == 0; - break; - case StatePosition.Parameter: - MacroParameter parameter = _macro.Parameters[_state.ParameterIndex]; - XPathNavigator? nav = parameter.NavigatorValue; - if (parameter.WrapNavigatorInNodes || nav != null) - { - isEmpty = false; - } - else - { - var s = _macro.Parameters[_state.ParameterIndex].StringValue; - isEmpty = s == null; - } - - break; - case StatePosition.ParameterNavigator: - isEmpty = _state.ParameterNavigator?.IsEmptyElement ?? true; - break; - case StatePosition.ParameterNodes: - isEmpty = _macro.Parameters[_state.ParameterIndex].NavigatorValue == null; - break; - case StatePosition.ParameterAttribute: - case StatePosition.ParameterText: - case StatePosition.Root: - throw new InvalidOperationException("Not an element."); - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn(isEmpty); - return isEmpty; - } - } - - /// - /// Determines whether the current XPathNavigator is at the same position as the specified XPathNavigator. - /// - /// The XPathNavigator to compare to this XPathNavigator. - /// true if the two XPathNavigator objects have the same position; otherwise, false. - public override bool IsSamePosition(XPathNavigator nav) - { - DebugEnter("IsSamePosition"); - bool isSame; - - switch (_state.Position) - { - case StatePosition.ParameterNavigator: - case StatePosition.Macro: - case StatePosition.Parameter: - case StatePosition.ParameterAttribute: - case StatePosition.ParameterNodes: - case StatePosition.ParameterText: - case StatePosition.Root: - var other = nav as MacroNavigator; - isSame = other != null && other._macro == _macro && _state.IsSamePosition(other._state); - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn(isSame); - return isSame; - } - - /// - /// Gets the qualified name of the current node. - /// - public override string Name - { - get - { - DebugEnter("Name"); - string name; - - switch (_state.Position) - { - case StatePosition.Macro: - name = "macro"; - break; - case StatePosition.Parameter: - name = _macro.Parameters[_state.ParameterIndex].Name; - break; - case StatePosition.ParameterAttribute: - name = _macro.Parameters[_state.ParameterIndex].Attributes?[_state.ParameterAttributeIndex].Key ?? string.Empty; - break; - case StatePosition.ParameterNavigator: - name = _state.ParameterNavigator?.Name ?? string.Empty; - break; - case StatePosition.ParameterNodes: - name = "nodes"; - break; - case StatePosition.ParameterText: - case StatePosition.Root: - name = string.Empty; - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn("\"{0}\"", name); - return name; - } - } - - /// - /// Gets the Name of the current node without any namespace prefix. - /// - public override string LocalName - { - get - { - DebugEnter("LocalName"); - var name = Name; - DebugReturn("\"{0}\"", name); - return name; - } - } - - /// - /// Moves the XPathNavigator to the same position as the specified XPathNavigator. - /// - /// The XPathNavigator positioned on the node that you want to move to. - /// Returns true if the XPathNavigator is successful moving to the same position as the specified XPathNavigator; - /// otherwise, false. If false, the position of the XPathNavigator is unchanged. - public override bool MoveTo(XPathNavigator nav) - { - DebugEnter("MoveTo"); - - var other = nav as MacroNavigator; - var succ = false; - - if (other != null && other._macro == _macro) - { - _state = other._state.Clone(); - DebugState(); - succ = true; - } - - DebugReturn(succ); - return succ; - } - - /// - /// Moves the XPathNavigator to the first attribute of the current node. - /// - /// Returns true if the XPathNavigator is successful moving to the first attribute of the current node; - /// otherwise, false. If false, the position of the XPathNavigator is unchanged. - public override bool MoveToFirstAttribute() - { - DebugEnter("MoveToFirstAttribute"); - bool succ; - - switch (_state.Position) - { - case StatePosition.ParameterNavigator: - succ = _state.ParameterNavigator?.MoveToFirstAttribute() ?? false; - break; - case StatePosition.Parameter: - if (_macro.Parameters[_state.ParameterIndex].Attributes != null) - { - _state.Position = StatePosition.ParameterAttribute; - _state.ParameterAttributeIndex = 0; - succ = true; - DebugState(); - } - else - { - succ = false; - } - - break; - case StatePosition.ParameterAttribute: - case StatePosition.ParameterNodes: - case StatePosition.Macro: - case StatePosition.ParameterText: - case StatePosition.Root: - succ = false; - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn(succ); - return succ; - } - - /// - /// Moves the XPathNavigator to the first child node of the current node. - /// - /// Returns true if the XPathNavigator is successful moving to the first child node of the current node; - /// otherwise, false. If false, the position of the XPathNavigator is unchanged. - public override bool MoveToFirstChild() - { - DebugEnter("MoveToFirstChild"); - bool succ; - - switch (_state.Position) - { - case StatePosition.Macro: - if (_macro.Parameters.Length == 0) - { - succ = false; - } - else - { - _state.ParameterIndex = 0; - _state.Position = StatePosition.Parameter; - succ = true; - } - break; - case StatePosition.Parameter: - MacroParameter parameter = _macro.Parameters[_state.ParameterIndex]; - XPathNavigator? nav = parameter.NavigatorValue; - if (parameter.WrapNavigatorInNodes) - { - _state.Position = StatePosition.ParameterNodes; - DebugState(); - succ = true; - } - else if (nav != null) - { - nav = nav.Clone(); // never use the raw parameter's navigator - nav.MoveToFirstChild(); - _state.ParameterNavigator = nav; - _state.ParameterNavigatorDepth = 0; - _state.Position = StatePosition.ParameterNavigator; - DebugState(); - succ = true; - } - else - { - var s = _macro.Parameters[_state.ParameterIndex].StringValue; - if (s != null) - { - _state.Position = StatePosition.ParameterText; - DebugState(); - succ = true; - } - else - { - succ = false; - } - } - - break; - case StatePosition.ParameterNavigator: - if (_state.ParameterNavigatorDepth == _macro.Parameters[_state.ParameterIndex].MaxNavigatorDepth) - { - succ = false; - } - else - { - // move to first doc child => increment depth, else (property child) do nothing - succ = _state.ParameterNavigator?.MoveToFirstChild() ?? false; - if (succ && IsDoc(_state.ParameterNavigator)) - { - ++_state.ParameterNavigatorDepth; - DebugState(); - } - } - break; - case StatePosition.ParameterNodes: - if (_macro.Parameters[_state.ParameterIndex].NavigatorValue != null) - { - // never use the raw parameter's navigator - _state.ParameterNavigator = _macro.Parameters[_state.ParameterIndex].NavigatorValue?.Clone(); - _state.Position = StatePosition.ParameterNavigator; - succ = true; - DebugState(); - } - else - { - succ = false; - } - - break; - case StatePosition.ParameterAttribute: - case StatePosition.ParameterText: - succ = false; - break; - case StatePosition.Root: - _state.Position = StatePosition.Macro; - DebugState(); - succ = true; - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn(succ); - return succ; - } - - /// - /// Moves the XPathNavigator to the first namespace node that matches the XPathNamespaceScope specified. - /// - /// An XPathNamespaceScope value describing the namespace scope. - /// Returns true if the XPathNavigator is successful moving to the first namespace node; - /// otherwise, false. If false, the position of the XPathNavigator is unchanged. - public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) - { - DebugEnter("MoveToFirstNamespace"); - DebugReturn(false); - return false; - } - - /// - /// Moves the XPathNavigator to the next namespace node matching the XPathNamespaceScope specified. - /// - /// An XPathNamespaceScope value describing the namespace scope. - /// Returns true if the XPathNavigator is successful moving to the next namespace node; - /// otherwise, false. If false, the position of the XPathNavigator is unchanged. - public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) - { - DebugEnter("MoveToNextNamespace"); - DebugReturn(false); - return false; - } - - /// - /// Moves to the node that has an attribute of type ID whose value matches the specified String. - /// - /// A String representing the ID value of the node to which you want to move. - /// true if the XPathNavigator is successful moving; otherwise, false. - /// If false, the position of the navigator is unchanged. - public override bool MoveToId(string id) - { - DebugEnter("MoveToId"); - // impossible to implement since parameters can contain duplicate fragments of the - // main xml and therefore there can be duplicate unique node identifiers. - DebugReturn("NotImplementedException"); - throw new NotImplementedException(); - } - - /// - /// Moves the XPathNavigator to the next sibling node of the current node. - /// - /// true if the XPathNavigator is successful moving to the next sibling node; - /// otherwise, false if there are no more siblings or if the XPathNavigator is currently - /// positioned on an attribute node. If false, the position of the XPathNavigator is unchanged. - public override bool MoveToNext() - { - DebugEnter("MoveToNext"); - bool succ; - - switch (_state.Position) - { - case StatePosition.Parameter: - if (_state.ParameterIndex == _macro.Parameters.Length - 1) - { - succ = false; - } - else - { - ++_state.ParameterIndex; - DebugState(); - succ = true; - } - break; - case StatePosition.ParameterNavigator: - var wasDoc = IsDoc(_state.ParameterNavigator); - succ = _state.ParameterNavigator?.MoveToNext() ?? false; - if (succ && !wasDoc && IsDoc(_state.ParameterNavigator)) - { - // move to first doc child => increment depth, else (another property child) do nothing - if (_state.ParameterNavigatorDepth == _macro.Parameters[_state.ParameterIndex].MaxNavigatorDepth) - { - _state.ParameterNavigator?.MoveToPrevious(); - succ = false; - } - else - { - ++_state.ParameterNavigatorDepth; - DebugState(); - } - } - break; - case StatePosition.ParameterNodes: - case StatePosition.ParameterAttribute: - case StatePosition.ParameterText: - case StatePosition.Macro: - case StatePosition.Root: - succ = false; - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn(succ); - return succ; - } - - /// - /// Moves the XPathNavigator to the previous sibling node of the current node. - /// - /// Returns true if the XPathNavigator is successful moving to the previous sibling node; - /// otherwise, false if there is no previous sibling node or if the XPathNavigator is currently - /// positioned on an attribute node. If false, the position of the XPathNavigator is unchanged. - public override bool MoveToPrevious() - { - DebugEnter("MoveToPrevious"); - bool succ; - - switch (_state.Position) - { - case StatePosition.Parameter: - if (_state.ParameterIndex == -1) - { - succ = false; - } - else - { - --_state.ParameterIndex; - DebugState(); - succ = true; - } - break; - case StatePosition.ParameterNavigator: - var wasDoc = IsDoc(_state.ParameterNavigator); - succ = _state.ParameterNavigator?.MoveToPrevious() ?? false; - if (succ && wasDoc && !IsDoc(_state.ParameterNavigator)) - { - // move from doc child back to property child => decrement depth - --_state.ParameterNavigatorDepth; - DebugState(); - } - break; - case StatePosition.ParameterAttribute: - case StatePosition.ParameterNodes: - case StatePosition.ParameterText: - case StatePosition.Macro: - case StatePosition.Root: - succ = false; - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn(succ); - return succ; - } - - /// - /// Moves the XPathNavigator to the next attribute. - /// - /// Returns true if the XPathNavigator is successful moving to the next attribute; - /// false if there are no more attributes. If false, the position of the XPathNavigator is unchanged. - public override bool MoveToNextAttribute() - { - DebugEnter("MoveToNextAttribute"); - bool succ; - - switch (_state.Position) - { - case StatePosition.ParameterNavigator: - succ = _state.ParameterNavigator?.MoveToNextAttribute() ?? false; - break; - case StatePosition.ParameterAttribute: - if (_state.ParameterAttributeIndex == _macro.Parameters[_state.ParameterIndex].Attributes?.Length - 1) - { - succ = false; - } - else - { - ++_state.ParameterAttributeIndex; - DebugState(); - succ = true; - } - break; - case StatePosition.Parameter: - case StatePosition.ParameterNodes: - case StatePosition.ParameterText: - case StatePosition.Macro: - case StatePosition.Root: - succ = false; - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn(succ); - return succ; - } - - /// - /// Moves the XPathNavigator to the parent node of the current node. - /// - /// Returns true if the XPathNavigator is successful moving to the parent node of the current node; - /// otherwise, false. If false, the position of the XPathNavigator is unchanged. - public override bool MoveToParent() - { - DebugEnter("MoveToParent"); - bool succ; - - switch (_state.Position) - { - case StatePosition.Macro: - _state.Position = StatePosition.Root; - DebugState(); - succ = true; - break; - case StatePosition.Parameter: - _state.Position = StatePosition.Macro; - DebugState(); - succ = true; - break; - case StatePosition.ParameterAttribute: - case StatePosition.ParameterNodes: - _state.Position = StatePosition.Parameter; - DebugState(); - succ = true; - break; - case StatePosition.ParameterNavigator: - var wasDoc = IsDoc(_state.ParameterNavigator); - succ = _state.ParameterNavigator?.MoveToParent() ?? false; - if (succ) - { - // move from doc child => decrement depth - if (wasDoc && --_state.ParameterNavigatorDepth == 0) - { - _state.Position = StatePosition.Parameter; - _state.ParameterNavigator = null; - DebugState(); - } - } - break; - case StatePosition.ParameterText: - _state.Position = StatePosition.Parameter; - DebugState(); - succ = true; - break; - case StatePosition.Root: - succ = false; - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn(succ); - return succ; - } - - /// - /// Moves the XPathNavigator to the root node that the current node belongs to. - /// - public override void MoveToRoot() - { - DebugEnter("MoveToRoot"); - - switch (_state.Position) - { - case StatePosition.ParameterNavigator: - _state.ParameterNavigator = null; - _state.ParameterNavigatorDepth = -1; - break; - case StatePosition.Parameter: - case StatePosition.ParameterText: - _state.ParameterIndex = -1; - break; - case StatePosition.ParameterAttribute: - case StatePosition.ParameterNodes: - case StatePosition.Macro: - case StatePosition.Root: - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - _state.Position = StatePosition.Root; - DebugState(); - - DebugReturn(); - } - - /// - /// Gets the base URI for the current node. - /// - public override string BaseURI - { - get { return string.Empty; } - } - - /// - /// Gets the XmlNameTable of the XPathNavigator. - /// - public override XmlNameTable NameTable - { - get { return _nameTable; } - } - - /// - /// Gets the namespace URI of the current node. - /// - public override string NamespaceURI - { - get { return string.Empty; } - } - - /// - /// Gets the XPathNodeType of the current node. - /// - public override XPathNodeType NodeType - { - get - { - DebugEnter("NodeType"); - XPathNodeType type; - - switch (_state.Position) - { - case StatePosition.Macro: - case StatePosition.Parameter: - case StatePosition.ParameterNodes: - type = XPathNodeType.Element; - break; - case StatePosition.ParameterNavigator: - type = _state.ParameterNavigator?.NodeType ?? XPathNodeType.Root; - break; - case StatePosition.ParameterAttribute: - type = XPathNodeType.Attribute; - break; - case StatePosition.ParameterText: - type = XPathNodeType.Text; - break; - case StatePosition.Root: - type = XPathNodeType.Root; - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn("\'{0}\'", type); - return type; - } - } - - /// - /// Gets the namespace prefix associated with the current node. - /// - public override string Prefix - { - get { return string.Empty; } - } - - /// - /// Gets the string value of the item. - /// - /// Does not fully behave as per the specs, as we report empty value on root and macro elements, and we start - /// reporting values only on parameter elements. This is because, otherwise, we would might dump the whole database - /// and it probably does not make sense at Umbraco level. - public override string Value - { - get - { - DebugEnter("Value"); - string value; - - XPathNavigator? nav; - switch (_state.Position) - { - case StatePosition.Parameter: - nav = _macro.Parameters[_state.ParameterIndex].NavigatorValue; - if (nav != null) - { - nav = nav.Clone(); // never use the raw parameter's navigator - nav.MoveToFirstChild(); - value = nav.Value; - } - else - { - var s = _macro.Parameters[_state.ParameterIndex].StringValue; - value = s ?? string.Empty; - } - break; - case StatePosition.ParameterAttribute: - value = _macro.Parameters[_state.ParameterIndex].Attributes?[_state.ParameterAttributeIndex].Value ?? string.Empty; - break; - case StatePosition.ParameterNavigator: - value = _state.ParameterNavigator?.Value ?? string.Empty; - break; - case StatePosition.ParameterNodes: - nav = _macro.Parameters[_state.ParameterIndex].NavigatorValue; - if (nav == null) - { - value = string.Empty; - } - else - { - nav = nav.Clone(); // never use the raw parameter's navigator - nav.MoveToFirstChild(); - value = nav.Value; - } - break; - case StatePosition.ParameterText: - value = _macro.Parameters[_state.ParameterIndex].StringValue ?? string.Empty; - break; - case StatePosition.Macro: - case StatePosition.Root: - value = string.Empty; - break; - default: - throw new InvalidOperationException("Invalid position."); - } - - DebugReturn("\"{0}\"", value); - return value; - } - } - - private static bool IsDoc(XPathNavigator? nav) - { - if (nav is null) - { - return false; - } - if (nav.NodeType != XPathNodeType.Element) - { - return false; - } - - XPathNavigator clone = nav.Clone(); - if (!clone.MoveToFirstAttribute()) - { - return false; - } - - do - { - if (clone.Name == "isDoc") - { - return true; - } - } - while (clone.MoveToNextAttribute()); - - return false; - } - - #region State management - - // the possible state positions - internal enum StatePosition - { - Root, - Macro, - Parameter, - ParameterAttribute, - ParameterText, - ParameterNodes, - ParameterNavigator - } - - // gets the state - // for unit tests only - internal State InternalState { get { return _state; } } - - // represents the XPathNavigator state - internal class State - { - public StatePosition Position { get; set; } - - // initialize a new state - private State(StatePosition position) - { - Position = position; - ParameterIndex = 0; - ParameterNavigatorDepth = 0; - ParameterAttributeIndex = 0; - } - - // initialize a new state - // used for creating the very first state - public State() - : this(StatePosition.Root) - { } - - // initialize a clone state - private State(State other) - { - Position = other.Position; - - ParameterIndex = other.ParameterIndex; - - if (Position == StatePosition.ParameterNavigator) - { - ParameterNavigator = other.ParameterNavigator?.Clone(); - ParameterNavigatorDepth = other.ParameterNavigatorDepth; - ParameterAttributeIndex = other.ParameterAttributeIndex; - } - } - - public State Clone() - { - return new State(this); - } - - // the index of the current element - public int ParameterIndex { get; set; } - - // the current depth within the element navigator - public int ParameterNavigatorDepth { get; set; } - - // the index of the current element's attribute - public int ParameterAttributeIndex { get; set; } - - // gets or sets the element navigator - public XPathNavigator? ParameterNavigator { get; set; } - - // gets a value indicating whether this state is at the same position as another one. - public bool IsSamePosition(State other) - { - if (other.ParameterNavigator is null || ParameterNavigator is null) - { - return false; - } - return other.Position == Position - && (Position != StatePosition.ParameterNavigator || other.ParameterNavigator.IsSamePosition(ParameterNavigator)) - && other.ParameterIndex == ParameterIndex - && other.ParameterAttributeIndex == ParameterAttributeIndex; - } - } - - #endregion - } -} diff --git a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.CoreServices.cs b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.CoreServices.cs index 138192ac5f..2bebd75c9c 100644 --- a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.CoreServices.cs +++ b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.CoreServices.cs @@ -167,7 +167,7 @@ public static partial class UmbracoBuilderExtensions builder.Services.AddSingleton(); builder.Services.AddSingleton(); - // both TinyMceValueConverter (in Core) and RteMacroRenderingValueConverter (in Web) will be + // both SimpleTinyMceValueConverter (in Core) and RteBlockRenderingValueConverter (in Infrastructure) will be // discovered when CoreBootManager configures the converters. We will remove the basic one defined // in core so that the more enhanced version is active. builder.PropertyValueConverters() @@ -389,8 +389,6 @@ public static partial class UmbracoBuilderExtensions .AddNotificationHandler() .AddNotificationHandler() .AddNotificationHandler() - .AddNotificationHandler() - .AddNotificationHandler() .AddNotificationHandler() .AddNotificationHandler() .AddNotificationHandler() diff --git a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Repositories.cs b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Repositories.cs index a7412acb06..647e2c9f29 100644 --- a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Repositories.cs +++ b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Repositories.cs @@ -2,7 +2,6 @@ using Microsoft.Extensions.DependencyInjection; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Persistence.Repositories; using Umbraco.Cms.Core.Services; -using Umbraco.Cms.Core.DynamicRoot; using Umbraco.Cms.Core.DynamicRoot.QuerySteps; using Umbraco.Cms.Infrastructure.Persistence.Repositories; using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement; @@ -39,7 +38,6 @@ public static partial class UmbracoBuilderExtensions builder.Services.AddSingleton(); builder.Services.AddUnique(factory => factory.GetRequiredService()); builder.Services.AddUnique(); - builder.Services.AddUnique(); builder.Services.AddUnique(); builder.Services.AddUnique(); builder.Services.AddUnique(); @@ -60,7 +58,6 @@ public static partial class UmbracoBuilderExtensions builder.Services.AddUnique(); builder.Services.AddUnique(); builder.Services.AddUnique(); - builder.Services.AddUnique(); builder.Services.AddUnique(); builder.Services.AddUnique(); builder.Services.AddUnique(); diff --git a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Services.cs b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Services.cs index 63204ec0b1..75249ce1db 100644 --- a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Services.cs +++ b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Services.cs @@ -72,7 +72,6 @@ public static partial class UmbracoBuilderExtensions factory.GetRequiredService(), factory.GetRequiredService(), factory.GetRequiredService(), - factory.GetRequiredService(), factory.GetRequiredService(), factory.GetRequiredService(), factory.GetRequiredService(), @@ -89,7 +88,6 @@ public static partial class UmbracoBuilderExtensions factory.GetRequiredService(), factory.GetRequiredService>(), factory.GetRequiredService(), - factory.GetRequiredService(), factory.GetRequiredService(), factory.GetRequiredService(), factory.GetRequiredService(), diff --git a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.TelemetryProviders.cs b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.TelemetryProviders.cs index f3fa362871..8c5651cf3e 100644 --- a/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.TelemetryProviders.cs +++ b/src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.TelemetryProviders.cs @@ -13,7 +13,6 @@ public static class UmbracoBuilder_TelemetryProviders builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); - builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); diff --git a/src/Umbraco.Infrastructure/Macros/MacroTagParser.cs b/src/Umbraco.Infrastructure/Macros/MacroTagParser.cs deleted file mode 100644 index 08559f786a..0000000000 --- a/src/Umbraco.Infrastructure/Macros/MacroTagParser.cs +++ /dev/null @@ -1,221 +0,0 @@ -using System.Text; -using System.Text.RegularExpressions; -using HtmlAgilityPack; -using Umbraco.Cms.Core.Xml; - -namespace Umbraco.Cms.Infrastructure.Macros; - -/// -/// Parses the macro syntax in a string and renders out it's contents -/// -public class MacroTagParser -{ - private static readonly Regex _macroRteContent = new( - @"()", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline); - - private static readonly Regex _macroPersistedFormat = - new( - @"(<\?UMBRACO_MACRO (?:.+?)??macroAlias=[""']([^""\'\n\r]+?)[""'].+?)(?:/>|>.*?)", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline); - - /// - /// This formats the persisted string to something useful for the rte so that the macro renders properly since we - /// persist all macro formats like {?UMBRACO_MACRO macroAlias=\"myMacro\" /} - /// - /// - /// The HTML attributes to be added to the div - /// - /// - /// This converts the persisted macro format to this: - /// {div class='umb-macro-holder'} - /// - /// {ins}Macro alias: {strong}My Macro{/strong}{/ins} - /// {/div} - /// - public static string FormatRichTextPersistedDataForEditor( - string persistedContent, - IDictionary htmlAttributes) => - _macroPersistedFormat.Replace(persistedContent, match => - { - if (match.Groups.Count >= 3) - { - var macroCanBeInlinedInParagraph = match.Value?.Contains("enableInlineMacro=\"1\"") ?? false; - var macroElementType = macroCanBeInlinedInParagraph ? "span" : "div"; - //
- var alias = match.Groups[2].Value; - var sb = new StringBuilder($"<{macroElementType} class=\"umb-macro-holder "); - if (macroCanBeInlinedInParagraph) - { - sb.Append("inlined-macro "); - } - // sb.Append(alias.ToSafeAlias()); - sb.Append("mceNonEditable\""); - foreach (KeyValuePair htmlAttribute in htmlAttributes) - { - sb.Append(" "); - sb.Append(htmlAttribute.Key); - sb.Append("=\""); - sb.Append(htmlAttribute.Value); - sb.Append("\""); - } - - sb.AppendLine(">"); - sb.Append(""); - sb.Append(""); - sb.Append("Macro alias: "); - sb.Append(""); - sb.Append(alias); - sb.Append($""); - return sb.ToString(); - } - - // replace with nothing if we couldn't find the syntax for whatever reason - return string.Empty; - }); - - /// - /// This formats the string content posted from a rich text editor that contains macro contents to be persisted. - /// - /// - /// - /// This is required because when editors are using the rte, the HTML that is contained in the editor might actually be - /// displaying - /// the entire macro content, when the data is submitted the editor will clear most of this data out but we'll still - /// need to parse it properly - /// and ensure the correct syntax is persisted to the db. - /// When a macro is inserted into the rte editor, the HTML will be: - /// {div class='umb-macro-holder'} - /// - /// This could be some macro content - /// {/div} - /// What this method will do is remove the {div} and parse out the commented special macro syntax: {?UMBRACO_MACRO - /// macroAlias=\"myMacro\" /} - /// since this is exactly how we need to persist it to the db. - /// - public static string FormatRichTextContentForPersistence(string rteContent) - { - if (string.IsNullOrEmpty(rteContent)) - { - return string.Empty; - } - - var html = new HtmlDocument(); - html.LoadHtml(rteContent); - - // get all the comment nodes we want - HtmlNodeCollection? commentNodes = html.DocumentNode.SelectNodes("//comment()[contains(., ' with the comment node itself. - foreach (HtmlNode? c in commentNodes) - { - HtmlNode? div = c.ParentNode; - HtmlNode? divContainer = div.ParentNode; - divContainer.ReplaceChild(c, div); - } - - var parsed = html.DocumentNode.OuterHtml; - - // now replace all the with nothing - return _macroRteContent.Replace(parsed, match => - { - if (match.Groups.Count >= 3) - { - // get the 3rd group which is the macro syntax - return match.Groups[2].Value; - } - - // replace with nothing if we couldn't find the syntax for whatever reason - return string.Empty; - }); - } - - /// - /// This will accept a text block and search/parse it for macro markup. - /// When either a text block or a a macro is found, it will call the callback method. - /// - /// - /// - /// - /// - /// - /// This method simply parses the macro contents, it does not create a string or result, - /// this is up to the developer calling this method to implement this with the callbacks. - /// - public static void ParseMacros( - string text, - Action textFoundCallback, - Action> macroFoundCallback) - { - if (textFoundCallback == null) - { - throw new ArgumentNullException("textFoundCallback"); - } - - if (macroFoundCallback == null) - { - throw new ArgumentNullException("macroFoundCallback"); - } - - var elementText = text; - - var fieldResult = new StringBuilder(elementText); - - // NOTE: This is legacy code, this is definitely not the correct way to do a while loop! :) - var stop = false; - while (!stop) - { - var tagIndex = fieldResult.ToString().ToLower().IndexOf(" -1) - { - var tempElementContent = string.Empty; - - // text block found, call the call back method - textFoundCallback(fieldResult.ToString().Substring(0, tagIndex)); - - fieldResult.Remove(0, tagIndex); - - var tag = fieldResult.ToString().Substring(0, fieldResult.ToString().IndexOf(">", StringComparison.InvariantCulture) + 1); - Dictionary attributes = XmlHelper.GetAttributesFromElement(tag); - - // Check whether it's a single tag () or a tag with children (...) - if (tag.Substring(tag.Length - 2, 1) != "/" && tag.IndexOf(" ", StringComparison.InvariantCulture) > -1) - { - var closingTag = ""; - - // Tag with children are only used when a macro is inserted by the umbraco-editor, in the - // following format: "", so we - // need to delete extra information inserted which is the image-tag and the closing - // umbraco_macro tag - if (fieldResult.ToString().IndexOf(closingTag, StringComparison.InvariantCulture) > -1) - { - fieldResult.Remove(0, fieldResult.ToString().IndexOf(closingTag, StringComparison.InvariantCulture)); - } - } - - var macroAlias = attributes.ContainsKey("macroalias") ? attributes["macroalias"] : attributes["alias"]; - - // call the callback now that we have the macro parsed - macroFoundCallback(macroAlias, attributes); - - fieldResult.Remove(0, fieldResult.ToString().IndexOf(">", StringComparison.InvariantCulture) + 1); - fieldResult.Insert(0, tempElementContent); - } - else - { - // text block found, call the call back method - textFoundCallback(fieldResult.ToString()); - - stop = true; // break; - } - } - } -} diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs index fdd1da6407..23ddc6ce96 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs @@ -40,8 +40,6 @@ public class DatabaseSchemaCreator typeof(LanguageTextDto), typeof(DomainDto), typeof(LogDto), - typeof(MacroDto), - typeof(MacroPropertyDto), typeof(MemberPropertyTypeDto), typeof(MemberDto), typeof(Member2MemberGroupDto), diff --git a/src/Umbraco.Infrastructure/Migrations/Upgrade/Common/DeleteKeysAndIndexes.cs b/src/Umbraco.Infrastructure/Migrations/Upgrade/Common/DeleteKeysAndIndexes.cs index 23f3928147..cb5857c828 100644 --- a/src/Umbraco.Infrastructure/Migrations/Upgrade/Common/DeleteKeysAndIndexes.cs +++ b/src/Umbraco.Infrastructure/Migrations/Upgrade/Common/DeleteKeysAndIndexes.cs @@ -24,8 +24,6 @@ public class DeleteKeysAndIndexes : MigrationBase "cmsDocument", "cmsDocumentType", "cmsLanguageText", - "cmsMacro", - "cmsMacroProperty", "cmsMedia", "cmsMember", "cmsMember2MemberGroup", diff --git a/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs b/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs index f394ae13b1..1dd09d4171 100644 --- a/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs +++ b/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs @@ -74,5 +74,6 @@ public class UmbracoPlan : MigrationPlan To("{7FC5AC9B-6F56-415B-913E-4A900629B853}"); To("{1539A010-2EB5-4163-8518-4AE2AA98AFC6}"); To("{C567DE81-DF92-4B99-BEA8-CD34EF99DA5D}"); + To("{0D82C836-96DD-480D-A924-7964E458BD34}"); } } diff --git a/src/Umbraco.Infrastructure/Migrations/Upgrade/V_14_0_0/DeleteMacroTables.cs b/src/Umbraco.Infrastructure/Migrations/Upgrade/V_14_0_0/DeleteMacroTables.cs new file mode 100644 index 0000000000..0af6c94098 --- /dev/null +++ b/src/Umbraco.Infrastructure/Migrations/Upgrade/V_14_0_0/DeleteMacroTables.cs @@ -0,0 +1,22 @@ +namespace Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_14_0_0; + +public class DeleteMacroTables : MigrationBase +{ + public DeleteMacroTables(IMigrationContext context) + : base(context) + { + } + + protected override void Migrate() + { + if (TableExists("cmsMacroProperty")) + { + Delete.Table("cmsMacroProperty").Do(); + } + + if (TableExists("cmsMacro")) + { + Delete.Table("cmsMacro").Do(); + } + } +} diff --git a/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs b/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs index 28f7cee140..2855b021f6 100644 --- a/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs +++ b/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs @@ -26,7 +26,6 @@ namespace Umbraco.Cms.Infrastructure.Packaging private readonly IDataValueEditorFactory _dataValueEditorFactory; private readonly ILogger _logger; private readonly IFileService _fileService; - private readonly IMacroService _macroService; private readonly ILocalizationService _localizationService; private readonly IDataTypeService _dataTypeService; private readonly PropertyEditorCollection _propertyEditors; @@ -43,7 +42,6 @@ namespace Umbraco.Cms.Infrastructure.Packaging IDataValueEditorFactory dataValueEditorFactory, ILogger logger, IFileService fileService, - IMacroService macroService, ILocalizationService localizationService, IDataTypeService dataTypeService, IEntityService entityService, @@ -59,7 +57,6 @@ namespace Umbraco.Cms.Infrastructure.Packaging _dataValueEditorFactory = dataValueEditorFactory; _logger = logger; _fileService = fileService; - _macroService = macroService; _localizationService = localizationService; _dataTypeService = dataTypeService; _entityService = entityService; @@ -79,7 +76,6 @@ namespace Umbraco.Cms.Infrastructure.Packaging IDataValueEditorFactory dataValueEditorFactory, ILogger logger, IFileService fileService, - IMacroService macroService, ILocalizationService localizationService, IDataTypeService dataTypeService, IEntityService entityService, @@ -97,7 +93,6 @@ namespace Umbraco.Cms.Infrastructure.Packaging dataValueEditorFactory, logger, fileService, - macroService, localizationService, dataTypeService, entityService, @@ -125,8 +120,6 @@ namespace Umbraco.Cms.Infrastructure.Packaging out IEnumerable dataTypeEntityContainersInstalled), LanguagesInstalled = ImportLanguages(compiledPackage.Languages, userId), DictionaryItemsInstalled = ImportDictionaryItems(compiledPackage.DictionaryItems, userId), - MacrosInstalled = ImportMacros(compiledPackage.Macros, userId), - MacroPartialViewsInstalled = ImportMacroPartialViews(compiledPackage.MacroPartialViews, userId), TemplatesInstalled = ImportTemplates(compiledPackage.Templates.ToList(), userId), DocumentTypesInstalled = ImportDocumentTypes(compiledPackage.DocumentTypes, userId, @@ -1523,153 +1516,6 @@ namespace Umbraco.Cms.Infrastructure.Packaging #endregion - #region Macros - - /// - /// Imports and saves the 'Macros' part of a package xml as a list of - /// - /// Xml to import - /// Optional id of the User performing the operation - /// - public IReadOnlyList ImportMacros( - IEnumerable macroElements, - int userId) - { - var macros = macroElements.Select(ParseMacroElement).ToList(); - - foreach (IMacro macro in macros) - { - _macroService.Save(macro, userId); - } - - return macros; - } - - public IReadOnlyList ImportMacroPartialViews(IEnumerable macroPartialViewsElements, - int userId) - { - var result = new List(); - - foreach (XElement macroPartialViewXml in macroPartialViewsElements) - { - var path = macroPartialViewXml.AttributeValue("path"); - if (path == null) - { - throw new InvalidOperationException("No path attribute found"); - } - - // Remove prefix to maintain backwards compatibility - if (path.StartsWith(Constants.SystemDirectories.MacroPartials)) - { - path = path.Substring(Constants.SystemDirectories.MacroPartials.Length); - } - else if (path.StartsWith("~")) - { - _logger.LogWarning( - "Importing macro partial views outside of the Views/MacroPartials directory is not supported: {Path}", - path); - continue; - } - - IPartialView? macroPartialView = _fileService.GetPartialViewMacro(path); - - // only update if it doesn't exist - if (macroPartialView == null) - { - var content = macroPartialViewXml.Value ?? string.Empty; - - macroPartialView = new PartialView(PartialViewType.PartialViewMacro, path) {Content = content}; - _fileService.SavePartialViewMacro(macroPartialView, userId); - result.Add(macroPartialView); - } - } - - return result; - } - - private IMacro ParseMacroElement(XElement macroElement) - { - var macroKey = Guid.Parse(macroElement.Element("key")!.Value); - var macroName = macroElement.Element("name")?.Value; - var macroAlias = macroElement.Element("alias")!.Value; - var macroSource = macroElement.Element("macroSource")!.Value; - - //Following xml elements are treated as nullable properties - XElement? useInEditorElement = macroElement.Element("useInEditor"); - var useInEditor = false; - if (useInEditorElement != null && string.IsNullOrEmpty((string)useInEditorElement) == false) - { - useInEditor = bool.Parse(useInEditorElement.Value); - } - - XElement? cacheDurationElement = macroElement.Element("refreshRate"); - var cacheDuration = 0; - if (cacheDurationElement != null && string.IsNullOrEmpty((string)cacheDurationElement) == false) - { - cacheDuration = int.Parse(cacheDurationElement.Value, CultureInfo.InvariantCulture); - } - - XElement? cacheByMemberElement = macroElement.Element("cacheByMember"); - var cacheByMember = false; - if (cacheByMemberElement != null && string.IsNullOrEmpty((string)cacheByMemberElement) == false) - { - cacheByMember = bool.Parse(cacheByMemberElement.Value); - } - - XElement? cacheByPageElement = macroElement.Element("cacheByPage"); - var cacheByPage = false; - if (cacheByPageElement != null && string.IsNullOrEmpty((string)cacheByPageElement) == false) - { - cacheByPage = bool.Parse(cacheByPageElement.Value); - } - - XElement? dontRenderElement = macroElement.Element("dontRender"); - var dontRender = true; - if (dontRenderElement != null && string.IsNullOrEmpty((string)dontRenderElement) == false) - { - dontRender = bool.Parse(dontRenderElement.Value); - } - - var existingMacro = _macroService.GetById(macroKey) as Macro; - Macro macro = existingMacro ?? new Macro(_shortStringHelper, macroAlias, macroName, macroSource, - cacheByPage, cacheByMember, dontRender, useInEditor, cacheDuration) {Key = macroKey}; - - XElement? properties = macroElement.Element("properties"); - if (properties != null) - { - int sortOrder = 0; - foreach (XElement property in properties.Elements()) - { - Guid propertyKey = property.RequiredAttributeValue("key"); - var propertyName = property.Attribute("name")?.Value; - var propertyAlias = property.Attribute("alias")!.Value; - var editorAlias = property.Attribute("propertyType")!.Value; - XAttribute? sortOrderAttribute = property.Attribute("sortOrder"); - if (sortOrderAttribute != null) - { - sortOrder = int.Parse(sortOrderAttribute.Value, CultureInfo.InvariantCulture); - } - - if (macro.Properties.Values.Any(x => - string.Equals(x.Alias, propertyAlias, StringComparison.OrdinalIgnoreCase))) - { - continue; - } - - macro.Properties.Add(new MacroProperty(propertyAlias, propertyName, sortOrder, editorAlias) - { - Key = propertyKey - }); - - sortOrder++; - } - } - - return macro; - } - - #endregion - public IReadOnlyList ImportScripts(IEnumerable scriptElements, int userId) { var result = new List(); @@ -1722,7 +1568,7 @@ namespace Umbraco.Cms.Infrastructure.Packaging { var content = partialViewXml.Value ?? string.Empty; - partialView = new PartialView(PartialViewType.PartialView, path) {Content = content}; + partialView = new PartialView(path) {Content = content}; _fileService.SavePartialView(partialView, userId); result.Add(partialView); } diff --git a/src/Umbraco.Infrastructure/Packaging/PackageInstallation.cs b/src/Umbraco.Infrastructure/Packaging/PackageInstallation.cs index ecd17fac4f..6d572cb29c 100644 --- a/src/Umbraco.Infrastructure/Packaging/PackageInstallation.cs +++ b/src/Umbraco.Infrastructure/Packaging/PackageInstallation.cs @@ -38,7 +38,7 @@ public class PackageInstallation : IPackageInstallation InstallationSummary installationSummary = _packageDataInstallation.InstallPackageData(compiledPackage, userId); - // Make sure the definition is up to date with everything (note: macro partial views are embedded in macros) + // Make sure the definition is up to date with everything foreach (IDataType x in installationSummary.DataTypesInstalled) { packageDefinition.DataTypes.Add(x.Id.ToInvariantString()); @@ -54,11 +54,6 @@ public class PackageInstallation : IPackageInstallation packageDefinition.DictionaryItems.Add(x.Id.ToInvariantString()); } - foreach (IMacro x in installationSummary.MacrosInstalled) - { - packageDefinition.Macros.Add(x.Id.ToInvariantString()); - } - foreach (ITemplate x in installationSummary.TemplatesInstalled) { packageDefinition.Templates.Add(x.Id.ToInvariantString()); diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/MacroDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/MacroDto.cs deleted file mode 100644 index eb46f8f5b9..0000000000 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/MacroDto.cs +++ /dev/null @@ -1,59 +0,0 @@ -using NPoco; -using Umbraco.Cms.Core; -using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations; - -namespace Umbraco.Cms.Infrastructure.Persistence.Dtos; - -[TableName(Constants.DatabaseSchema.Tables.Macro)] -[PrimaryKey("id")] -[ExplicitColumns] -internal class MacroDto -{ - [Column("id")] - [PrimaryKeyColumn] - public int Id { get; set; } - - [Column("uniqueId")] - [Index(IndexTypes.UniqueNonClustered, Name = "IX_cmsMacro_UniqueId")] - public Guid UniqueId { get; set; } - - [Column("macroUseInEditor")] - [Constraint(Default = "0")] - public bool UseInEditor { get; set; } - - [Column("macroRefreshRate")] - [Constraint(Default = "0")] - public int RefreshRate { get; set; } - - [Column("macroAlias")] - [Index(IndexTypes.UniqueNonClustered, Name = "IX_cmsMacroPropertyAlias")] - public string Alias { get; set; } = string.Empty; - - [Column("macroName")] - [NullSetting(NullSetting = NullSettings.Null)] - public string? Name { get; set; } - - [Column("macroCacheByPage")] - [Constraint(Default = "1")] - public bool CacheByPage { get; set; } - - [Column("macroCachePersonalized")] - [Constraint(Default = "0")] - public bool CachePersonalized { get; set; } - - [Column("macroDontRender")] - [Constraint(Default = "0")] - public bool DontRender { get; set; } - - [Column("macroSource")] - [NullSetting(NullSetting = NullSettings.NotNull)] - public string MacroSource { get; set; } = null!; - - [Column("macroType")] - [NullSetting(NullSetting = NullSettings.NotNull)] - public int MacroType { get; set; } - - [ResultColumn] - [Reference(ReferenceType.Many, ReferenceMemberName = "Macro")] - public List? MacroPropertyDtos { get; set; } -} diff --git a/src/Umbraco.Infrastructure/Persistence/Dtos/MacroPropertyDto.cs b/src/Umbraco.Infrastructure/Persistence/Dtos/MacroPropertyDto.cs deleted file mode 100644 index 98eb9de0b6..0000000000 --- a/src/Umbraco.Infrastructure/Persistence/Dtos/MacroPropertyDto.cs +++ /dev/null @@ -1,39 +0,0 @@ -using NPoco; -using Umbraco.Cms.Core; -using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations; - -namespace Umbraco.Cms.Infrastructure.Persistence.Dtos; - -[TableName(Constants.DatabaseSchema.Tables.MacroProperty)] -[PrimaryKey("id")] -[ExplicitColumns] -internal class MacroPropertyDto -{ - [Column("id")] - [PrimaryKeyColumn] - public int Id { get; set; } - - // important to use column name != cmsMacro.uniqueId (fix in v8) - [Column("uniquePropertyId")] - [Index(IndexTypes.UniqueNonClustered, Name = "IX_cmsMacroProperty_UniquePropertyId")] - public Guid UniqueId { get; set; } - - [Column("editorAlias")] - public string EditorAlias { get; set; } = null!; - - [Column("macro")] - [ForeignKey(typeof(MacroDto))] - [Index(IndexTypes.UniqueNonClustered, Name = "IX_cmsMacroProperty_Alias", ForColumns = "macro, macroPropertyAlias")] - public int Macro { get; set; } - - [Column("macroPropertySortOrder")] - [Constraint(Default = "0")] - public byte SortOrder { get; set; } - - [Column("macroPropertyAlias")] - [Length(50)] - public string Alias { get; set; } = null!; - - [Column("macroPropertyName")] - public string? Name { get; set; } -} diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/MacroFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/MacroFactory.cs deleted file mode 100644 index 3725a2be6a..0000000000 --- a/src/Umbraco.Infrastructure/Persistence/Factories/MacroFactory.cs +++ /dev/null @@ -1,80 +0,0 @@ -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Strings; -using Umbraco.Cms.Infrastructure.Persistence.Dtos; -using Umbraco.Extensions; - -namespace Umbraco.Cms.Infrastructure.Persistence.Factories; - -internal static class MacroFactory -{ - public static IMacro BuildEntity(IShortStringHelper shortStringHelper, MacroDto dto) - { - var model = new Macro(shortStringHelper, dto.Id, dto.UniqueId, dto.UseInEditor, dto.RefreshRate, dto.Alias, - dto.Name, dto.CacheByPage, dto.CachePersonalized, dto.DontRender, dto.MacroSource); - - try - { - model.DisableChangeTracking(); - - foreach (MacroPropertyDto p in dto.MacroPropertyDtos.EmptyNull()) - { - model.Properties.Add(new MacroProperty(p.Id, p.UniqueId, p.Alias, p.Name, p.SortOrder, p.EditorAlias)); - } - - // reset dirty initial properties (U4-1946) - model.ResetDirtyProperties(false); - return model; - } - finally - { - model.EnableChangeTracking(); - } - } - - public static MacroDto BuildDto(IMacro entity) - { - var dto = new MacroDto - { - UniqueId = entity.Key, - Alias = entity.Alias, - CacheByPage = entity.CacheByPage, - CachePersonalized = entity.CacheByMember, - DontRender = entity.DontRender, - Name = entity.Name, - MacroSource = entity.MacroSource, - RefreshRate = entity.CacheDuration, - UseInEditor = entity.UseInEditor, - MacroPropertyDtos = BuildPropertyDtos(entity), - MacroType = 7, // PartialView - }; - - if (entity.HasIdentity) - { - dto.Id = entity.Id; - } - - return dto; - } - - private static List BuildPropertyDtos(IMacro entity) - { - var list = new List(); - foreach (IMacroProperty p in entity.Properties) - { - var text = new MacroPropertyDto - { - UniqueId = p.Key, - Alias = p.Alias, - Name = p.Name, - Macro = entity.Id, - SortOrder = (byte)p.SortOrder, - EditorAlias = p.EditorAlias, - Id = p.Id, - }; - - list.Add(text); - } - - return list; - } -} diff --git a/src/Umbraco.Infrastructure/Persistence/Mappers/MacroMapper.cs b/src/Umbraco.Infrastructure/Persistence/Mappers/MacroMapper.cs deleted file mode 100644 index 2384f239c9..0000000000 --- a/src/Umbraco.Infrastructure/Persistence/Mappers/MacroMapper.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Infrastructure.Persistence.Dtos; - -namespace Umbraco.Cms.Infrastructure.Persistence.Mappers; - -[MapperFor(typeof(Macro))] -[MapperFor(typeof(IMacro))] -internal sealed class MacroMapper : BaseMapper -{ - public MacroMapper(Lazy sqlContext, MapperConfigurationStore maps) - : base(sqlContext, maps) - { - } - - protected override void DefineMaps() - { - DefineMap(nameof(Macro.Id), nameof(MacroDto.Id)); - DefineMap(nameof(Macro.Alias), nameof(MacroDto.Alias)); - DefineMap(nameof(Macro.CacheByPage), nameof(MacroDto.CacheByPage)); - DefineMap(nameof(Macro.CacheByMember), nameof(MacroDto.CachePersonalized)); - DefineMap(nameof(Macro.DontRender), nameof(MacroDto.DontRender)); - DefineMap(nameof(Macro.Name), nameof(MacroDto.Name)); - DefineMap(nameof(Macro.CacheDuration), nameof(MacroDto.RefreshRate)); - DefineMap(nameof(Macro.MacroSource), nameof(MacroDto.MacroSource)); - DefineMap(nameof(Macro.UseInEditor), nameof(MacroDto.UseInEditor)); - } -} diff --git a/src/Umbraco.Infrastructure/Persistence/Mappers/MapperCollectionBuilder.cs b/src/Umbraco.Infrastructure/Persistence/Mappers/MapperCollectionBuilder.cs index 3502e32752..12af3490b8 100644 --- a/src/Umbraco.Infrastructure/Persistence/Mappers/MapperCollectionBuilder.cs +++ b/src/Umbraco.Infrastructure/Persistence/Mappers/MapperCollectionBuilder.cs @@ -33,7 +33,6 @@ public class MapperCollectionBuilder : SetCollectionBuilderBase(); Add(); Add(); - Add(); Add(); Add(); Add(); diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/CreatedPackageSchemaRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/CreatedPackageSchemaRepository.cs index 05317b39e1..0eda72ccbe 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/CreatedPackageSchemaRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/CreatedPackageSchemaRepository.cs @@ -33,7 +33,6 @@ public class CreatedPackageSchemaRepository : ICreatedPackagesRepository private readonly FileSystems _fileSystems; private readonly IHostingEnvironment _hostingEnvironment; private readonly ILocalizationService _localizationService; - private readonly IMacroService _macroService; private readonly MediaFileManager _mediaFileManager; private readonly IMediaService _mediaService; private readonly IMediaTypeService _mediaTypeService; @@ -57,7 +56,6 @@ public class CreatedPackageSchemaRepository : ICreatedPackagesRepository IMediaTypeService mediaTypeService, IContentService contentService, MediaFileManager mediaFileManager, - IMacroService macroService, IContentTypeService contentTypeService, IScopeAccessor scopeAccessor, string? mediaFolderPath = null, @@ -73,7 +71,6 @@ public class CreatedPackageSchemaRepository : ICreatedPackagesRepository _mediaTypeService = mediaTypeService; _contentService = contentService; _mediaFileManager = mediaFileManager; - _macroService = macroService; _contentTypeService = contentTypeService; _scopeAccessor = scopeAccessor; _xmlParser = new PackageDefinitionXmlParser(); @@ -95,7 +92,6 @@ public class CreatedPackageSchemaRepository : ICreatedPackagesRepository IMediaTypeService mediaTypeService, IContentService contentService, MediaFileManager mediaFileManager, - IMacroService macroService, IContentTypeService contentTypeService, string? mediaFolderPath = null, string? tempFolderPath = null) @@ -112,7 +108,6 @@ public class CreatedPackageSchemaRepository : ICreatedPackagesRepository mediaTypeService, contentService, mediaFileManager, - macroService, contentTypeService, StaticServiceProvider.Instance.GetRequiredService(), mediaFolderPath, @@ -294,7 +289,6 @@ public class CreatedPackageSchemaRepository : ICreatedPackagesRepository PackageStylesheets(definition, root); PackageStaticFiles(definition.Scripts, root, "Scripts", "Script", _fileSystems.ScriptsFileSystem!); PackageStaticFiles(definition.PartialViews, root, "PartialViews", "View", _fileSystems.PartialViewsFileSystem!); - PackageMacros(definition, root); PackageDictionaryItems(definition, root); PackageLanguages(definition, root); PackageDataTypes(definition, root); @@ -529,37 +523,6 @@ public class CreatedPackageSchemaRepository : ICreatedPackagesRepository } } - private void PackageMacros(PackageDefinition definition, XContainer root) - { - var packagedMacros = new List(); - var macros = new XElement("Macros"); - foreach (var macroId in definition.Macros) - { - if (!int.TryParse(macroId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt)) - { - continue; - } - - XElement? macroXml = GetMacroXml(outInt, out IMacro? macro); - if (macroXml is null) - { - continue; - } - - macros.Add(macroXml); - packagedMacros.Add(macro!); - } - - root.Add(macros); - - // Get the partial views for macros and package those (exclude views outside of the default directory, e.g. App_Plugins\*\Views) - IEnumerable views = packagedMacros - .Where(x => x.MacroSource.StartsWith(Constants.SystemDirectories.MacroPartials)) - .Select(x => - x.MacroSource[Constants.SystemDirectories.MacroPartials.Length..].Replace('/', '\\')); - PackageStaticFiles(views, root, "MacroPartialViews", "View", _fileSystems.MacroPartialsFileSystem!); - } - private void PackageStylesheets(PackageDefinition definition, XContainer root) { var stylesheetsXml = new XElement("Stylesheets"); @@ -765,21 +728,6 @@ public class CreatedPackageSchemaRepository : ICreatedPackagesRepository return mediaStreams; } - /// - /// Gets a macros xml node - /// - private XElement? GetMacroXml(int macroId, out IMacro? macro) - { - macro = _macroService.GetById(macroId); - if (macro == null) - { - return null; - } - - XElement xml = _serializer.Serialize(macro); - return xml; - } - /// /// Converts a umbraco stylesheet to a package xml node /// diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MacroRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MacroRepository.cs deleted file mode 100644 index 67fe818358..0000000000 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/MacroRepository.cs +++ /dev/null @@ -1,266 +0,0 @@ -using Microsoft.Extensions.Logging; -using NPoco; -using Umbraco.Cms.Core; -using Umbraco.Cms.Core.Cache; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Models.Entities; -using Umbraco.Cms.Core.Persistence.Querying; -using Umbraco.Cms.Core.Persistence.Repositories; -using Umbraco.Cms.Core.Strings; -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; - -namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement; - -internal class MacroRepository : EntityRepositoryBase, IMacroRepository -{ - private readonly IRepositoryCachePolicy _macroByAliasCachePolicy; - private readonly IShortStringHelper _shortStringHelper; - - public MacroRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger, - IShortStringHelper shortStringHelper) - : base(scopeAccessor, cache, logger) - { - _shortStringHelper = shortStringHelper; - _macroByAliasCachePolicy = - new DefaultRepositoryCachePolicy(GlobalIsolatedCache, ScopeAccessor, DefaultOptions); - } - - public IMacro? Get(Guid id) - { - Sql sql = GetBaseQuery().Where(x => x.UniqueId == id); - return GetBySql(sql); - } - - public IEnumerable GetMany(params Guid[]? ids) => - ids?.Length > 0 ? ids.Select(Get).WhereNotNull() : GetAllNoIds(); - - public bool Exists(Guid id) => Get(id) != null; - - public IMacro? GetByAlias(string alias) => - _macroByAliasCachePolicy.Get(alias, PerformGetByAlias, PerformGetAllByAlias); - - public IEnumerable GetAllByAlias(string[] aliases) - { - if (aliases.Any() is false) - { - return base.GetMany(); - } - - return _macroByAliasCachePolicy.GetAll(aliases, PerformGetAllByAlias); - } - - protected override IMacro? PerformGet(int id) - { - Sql sql = GetBaseQuery(false); - sql.Where(GetBaseWhereClause(), new { id }); - return GetBySql(sql); - } - - protected override IEnumerable PerformGetAll(params int[]? ids) => - ids?.Length > 0 ? ids.Select(Get).WhereNotNull() : GetAllNoIds(); - - protected override IEnumerable PerformGetByQuery(IQuery query) - { - Sql sqlClause = GetBaseQuery(false); - var translator = new SqlTranslator(sqlClause, query); - Sql sql = translator.Translate(); - - return Database - .FetchOneToMany(x => x.MacroPropertyDtos, sql) - .Select(x => Get(x.Id)!); - } - - private IMacro? GetBySql(Sql sql) - { - MacroDto? macroDto = Database - .FetchOneToMany(x => x.MacroPropertyDtos, sql) - .FirstOrDefault(); - - if (macroDto == null) - { - return null; - } - - IMacro entity = MacroFactory.BuildEntity(_shortStringHelper, macroDto); - - // reset dirty initial properties (U4-1946) - ((BeingDirtyBase)entity).ResetDirtyProperties(false); - - return entity; - } - - private IMacro? PerformGetByAlias(string? alias) - { - IQuery query = Query().Where(x => x.Alias.Equals(alias)); - return PerformGetByQuery(query).FirstOrDefault(); - } - - private IEnumerable PerformGetAllByAlias(params string[]? aliases) - { - if (aliases is null || aliases.Any() is false) - { - return base.GetMany(); - } - - IQuery query = Query().Where(x => aliases.Contains(x.Alias)); - return PerformGetByQuery(query); - } - - private IEnumerable GetAllNoIds() - { - Sql sql = GetBaseQuery(false) - - // must be sorted this way for the relator to work - .OrderBy(x => x.Id); - - return Database - .FetchOneToMany(x => x.MacroPropertyDtos, sql) - .Transform(ConvertFromDtos) - .ToArray(); // do it now and once - } - - private IEnumerable ConvertFromDtos(IEnumerable dtos) - { - foreach (IMacro entity in dtos.Select(x => MacroFactory.BuildEntity(_shortStringHelper, x))) - { - // reset dirty initial properties (U4-1946) - ((BeingDirtyBase)entity).ResetDirtyProperties(false); - - yield return entity; - } - } - - protected override Sql GetBaseQuery(bool isCount) => - isCount ? Sql().SelectCount().From() : GetBaseQuery(); - - protected override string GetBaseWhereClause() => $"{Constants.DatabaseSchema.Tables.Macro}.id = @id"; - - private Sql GetBaseQuery() => - Sql() - .SelectAll() - .From() - .LeftJoin() - .On(left => left.Id, right => right.Macro); - - protected override IEnumerable GetDeleteClauses() - { - var list = new List - { - "DELETE FROM cmsMacroProperty WHERE macro = @id", "DELETE FROM cmsMacro WHERE id = @id", - }; - return list; - } - - protected override void PersistNewItem(IMacro entity) - { - entity.AddingEntity(); - - MacroDto dto = MacroFactory.BuildDto(entity); - - var id = Convert.ToInt32(Database.Insert(dto)); - entity.Id = id; - - if (dto.MacroPropertyDtos is not null) - { - foreach (MacroPropertyDto propDto in dto.MacroPropertyDtos) - { - // need to set the id explicitly here - propDto.Macro = id; - var propId = Convert.ToInt32(Database.Insert(propDto)); - entity.Properties[propDto.Alias].Id = propId; - } - } - - entity.ResetDirtyProperties(); - } - - protected override void PersistUpdatedItem(IMacro entity) - { - entity.UpdatingEntity(); - MacroDto dto = MacroFactory.BuildDto(entity); - - Database.Update(dto); - - // update the properties if they've changed - var macro = (Macro)entity; - if (macro.IsPropertyDirty("Properties") || macro.Properties.Values.Any(x => x.IsDirty())) - { - var ids = dto.MacroPropertyDtos?.Where(x => x.Id > 0).Select(x => x.Id).ToArray(); - if (ids?.Length > 0) - { - Database.Delete("WHERE macro=@macro AND id NOT IN (@ids)", new { macro = dto.Id, ids }); - } - else - { - Database.Delete("WHERE macro=@macro", new { macro = dto.Id }); - } - - // detect new aliases, replace with temp aliases - // this ensures that we don't have collisions, ever - var aliases = new Dictionary(); - if (dto.MacroPropertyDtos is null) - { - return; - } - - foreach (MacroPropertyDto propDto in dto.MacroPropertyDtos) - { - IMacroProperty? prop = macro.Properties.Values.FirstOrDefault(x => x.Id == propDto.Id); - if (prop == null) - { - throw new Exception("oops: property."); - } - - if (propDto.Id == 0 || prop.IsPropertyDirty("Alias")) - { - var tempAlias = Guid.NewGuid().ToString("N")[..8]; - aliases[tempAlias] = propDto.Alias; - propDto.Alias = tempAlias; - } - } - - // insert or update existing properties, with temp aliases - foreach (MacroPropertyDto propDto in dto.MacroPropertyDtos) - { - if (propDto.Id == 0) - { - // insert - propDto.Id = Convert.ToInt32(Database.Insert(propDto)); - macro.Properties[aliases[propDto.Alias]].Id = propDto.Id; - } - else - { - // update - IMacroProperty? property = macro.Properties.Values.FirstOrDefault(x => x.Id == propDto.Id); - if (property == null) - { - throw new Exception("oops: property."); - } - - if (property.IsDirty()) - { - Database.Update(propDto); - } - } - } - - // replace the temp aliases with the real ones - foreach (MacroPropertyDto propDto in dto.MacroPropertyDtos) - { - if (aliases.ContainsKey(propDto.Alias) == false) - { - continue; - } - - propDto.Alias = aliases[propDto.Alias]; - Database.Update(propDto); - } - } - - entity.ResetDirtyProperties(); - } -} diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/PartialViewMacroRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/PartialViewMacroRepository.cs deleted file mode 100644 index 37c6d67228..0000000000 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/PartialViewMacroRepository.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Umbraco.Cms.Core.IO; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Persistence.Repositories; - -namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement; - -internal class PartialViewMacroRepository : PartialViewRepository, IPartialViewMacroRepository -{ - public PartialViewMacroRepository(FileSystems fileSystems) - : base(fileSystems.MacroPartialsFileSystem) - { - } - - protected override PartialViewType ViewType => PartialViewType.PartialViewMacro; -} diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/PartialViewRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/PartialViewRepository.cs index ff751a9fe6..7e4d5d6817 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/PartialViewRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/PartialViewRepository.cs @@ -18,8 +18,6 @@ internal class PartialViewRepository : FileRepository, IPa { } - protected virtual PartialViewType ViewType => PartialViewType.PartialView; - public override IPartialView? Get(string? id) { if (FileSystem is null) @@ -41,7 +39,7 @@ internal class PartialViewRepository : FileRepository, IPa DateTime updated = FileSystem.GetLastModified(path).UtcDateTime; // var content = GetFileContent(path); - var view = new PartialView(ViewType, path, file => GetFileContent(file.OriginalPath)) + var view = new PartialView(path, file => GetFileContent(file.OriginalPath)) { // id can be the hash Id = path.GetHashCode(), @@ -62,10 +60,6 @@ internal class PartialViewRepository : FileRepository, IPa public override void Save(IPartialView entity) { var partialView = entity as PartialView; - if (partialView != null) - { - partialView.ViewType = ViewType; - } base.Save(entity); diff --git a/src/Umbraco.Infrastructure/PropertyEditors/RichTextPropertyEditor.cs b/src/Umbraco.Infrastructure/PropertyEditors/RichTextPropertyEditor.cs index 7949eb65db..006c273b56 100644 --- a/src/Umbraco.Infrastructure/PropertyEditors/RichTextPropertyEditor.cs +++ b/src/Umbraco.Infrastructure/PropertyEditors/RichTextPropertyEditor.cs @@ -4,7 +4,6 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.Logging; using Umbraco.Cms.Core.Cache; -using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Blocks; @@ -14,7 +13,6 @@ using Umbraco.Cms.Core.Serialization; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Core.Templates; -using Umbraco.Cms.Infrastructure.Macros; using Umbraco.Extensions; namespace Umbraco.Cms.Core.PropertyEditors; @@ -58,7 +56,7 @@ public class RichTextPropertyEditor : DataEditor new RichTextConfigurationEditor(_ioHelper); /// - /// A custom value editor to ensure that macro syntax is parsed when being persisted and formatted correctly for + /// A custom value editor to ensure that images and blocks are parsed when being persisted and formatted correctly for /// display in the editor /// internal class RichTextPropertyValueEditor : BlockValuePropertyValueEditorBase @@ -193,11 +191,7 @@ public class RichTextPropertyEditor : DataEditor return null; } - var propertyValueWithMediaResolved = _imageSourceParser.EnsureImageSources(richTextEditorValue.Markup); - var parsed = MacroTagParser.FormatRichTextPersistedDataForEditor( - propertyValueWithMediaResolved, - new Dictionary()); - richTextEditorValue.Markup = parsed; + richTextEditorValue.Markup = _imageSourceParser.EnsureImageSources(richTextEditorValue.Markup); // return json convertable object return CleanAndMapBlocks(richTextEditorValue, blockValue => MapBlockValueToEditor(property, blockValue)); @@ -235,8 +229,7 @@ public class RichTextPropertyEditor : DataEditor .GetAwaiter() .GetResult(); var editorValueWithMediaUrlsRemoved = _imageSourceParser.RemoveImageSources(parseAndSavedTempImages); - var parsed = MacroTagParser.FormatRichTextContentForPersistence(editorValueWithMediaUrlsRemoved); - var sanitized = _htmlSanitizer.Sanitize(parsed); + var sanitized = _htmlSanitizer.Sanitize(editorValueWithMediaUrlsRemoved); richTextEditorValue.Markup = sanitized.NullOrWhiteSpaceAsNull() ?? string.Empty; diff --git a/src/Umbraco.Infrastructure/PropertyEditors/ValueConverters/MarkdownEditorValueConverter.cs b/src/Umbraco.Infrastructure/PropertyEditors/ValueConverters/MarkdownEditorValueConverter.cs index 178778483d..fd3e4b83c9 100644 --- a/src/Umbraco.Infrastructure/PropertyEditors/ValueConverters/MarkdownEditorValueConverter.cs +++ b/src/Umbraco.Infrastructure/PropertyEditors/ValueConverters/MarkdownEditorValueConverter.cs @@ -28,7 +28,6 @@ public class MarkdownEditorValueConverter : PropertyValueConverterBase, IDeliver public override Type GetPropertyValueType(IPublishedPropertyType propertyType) => typeof(IHtmlEncodedString); - // PropertyCacheLevel.Content is ok here because that converter does not parse {locallink} nor executes macros public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType) => PropertyCacheLevel.Snapshot; diff --git a/src/Umbraco.Infrastructure/PropertyEditors/ValueConverters/RteMacroRenderingValueConverter.cs b/src/Umbraco.Infrastructure/PropertyEditors/ValueConverters/RteBlockRenderingValueConverter.cs similarity index 68% rename from src/Umbraco.Infrastructure/PropertyEditors/ValueConverters/RteMacroRenderingValueConverter.cs rename to src/Umbraco.Infrastructure/PropertyEditors/ValueConverters/RteBlockRenderingValueConverter.cs index c8fdefa508..9fc9cd00cd 100644 --- a/src/Umbraco.Infrastructure/PropertyEditors/ValueConverters/RteMacroRenderingValueConverter.cs +++ b/src/Umbraco.Infrastructure/PropertyEditors/ValueConverters/RteBlockRenderingValueConverter.cs @@ -2,24 +2,18 @@ // See LICENSE for more details. using System.Globalization; -using System.Text; using System.Text.RegularExpressions; using HtmlAgilityPack; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Blocks; using Umbraco.Cms.Core.Configuration.Models; -using Umbraco.Cms.Core.DependencyInjection; -using Umbraco.Cms.Core.Macros; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PropertyEditors.DeliveryApi; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Core.Templates; -using Umbraco.Cms.Core.Web; using Umbraco.Cms.Core.DeliveryApi; using Umbraco.Cms.Core.Models.Blocks; -using Umbraco.Cms.Infrastructure.Macros; using Umbraco.Cms.Core.Models.DeliveryApi; using Umbraco.Cms.Core.Serialization; using Umbraco.Cms.Infrastructure.Extensions; @@ -28,74 +22,31 @@ using Umbraco.Extensions; namespace Umbraco.Cms.Core.PropertyEditors.ValueConverters; /// -/// A value converter for TinyMCE that will ensure any macro content is rendered properly even when +/// A value converter for TinyMCE that will ensure any blocks content are rendered properly even when /// used dynamically. /// [DefaultPropertyValueConverter] -public class RteMacroRenderingValueConverter : SimpleTinyMceValueConverter, IDeliveryApiPropertyValueConverter +public class RteBlockRenderingValueConverter : SimpleTinyMceValueConverter, IDeliveryApiPropertyValueConverter { private readonly HtmlImageSourceParser _imageSourceParser; private readonly HtmlLocalLinkParser _linkParser; - private readonly IMacroRenderer _macroRenderer; - private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly HtmlUrlParser _urlParser; private readonly IApiRichTextElementParser _apiRichTextElementParser; private readonly IApiRichTextMarkupParser _apiRichTextMarkupParser; private readonly IPartialViewBlockEngine _partialViewBlockEngine; private readonly BlockEditorConverter _blockEditorConverter; private readonly IJsonSerializer _jsonSerializer; - private readonly ILogger _logger; + private readonly ILogger _logger; private readonly IApiElementBuilder _apiElementBuilder; private readonly RichTextBlockPropertyValueConstructorCache _constructorCache; private DeliveryApiSettings _deliveryApiSettings; - [Obsolete("Please use the constructor that takes all arguments. Will be removed in V14.")] - public RteMacroRenderingValueConverter(IUmbracoContextAccessor umbracoContextAccessor, IMacroRenderer macroRenderer, - HtmlLocalLinkParser linkParser, HtmlUrlParser urlParser, HtmlImageSourceParser imageSourceParser) - : this( - umbracoContextAccessor, - macroRenderer, - linkParser, - urlParser, - imageSourceParser, - StaticServiceProvider.Instance.GetRequiredService(), - StaticServiceProvider.Instance.GetRequiredService(), - StaticServiceProvider.Instance.GetRequiredService>()) - { - } - - [Obsolete("Please use the constructor that takes all arguments. Will be removed in V15.")] - public RteMacroRenderingValueConverter(IUmbracoContextAccessor umbracoContextAccessor, IMacroRenderer macroRenderer, - HtmlLocalLinkParser linkParser, HtmlUrlParser urlParser, HtmlImageSourceParser imageSourceParser, - IApiRichTextElementParser apiRichTextElementParser, IApiRichTextMarkupParser apiRichTextMarkupParser, IOptionsMonitor deliveryApiSettingsMonitor) - : this( - umbracoContextAccessor, - macroRenderer, - linkParser, - urlParser, - imageSourceParser, - apiRichTextElementParser, - apiRichTextMarkupParser, - StaticServiceProvider.Instance.GetRequiredService(), - StaticServiceProvider.Instance.GetRequiredService(), - StaticServiceProvider.Instance.GetRequiredService(), - StaticServiceProvider.Instance.GetRequiredService(), - StaticServiceProvider.Instance.GetRequiredService(), - StaticServiceProvider.Instance.GetRequiredService>(), - deliveryApiSettingsMonitor - ) - { - } - - public RteMacroRenderingValueConverter(IUmbracoContextAccessor umbracoContextAccessor, IMacroRenderer macroRenderer, - HtmlLocalLinkParser linkParser, HtmlUrlParser urlParser, HtmlImageSourceParser imageSourceParser, + public RteBlockRenderingValueConverter(HtmlLocalLinkParser linkParser, HtmlUrlParser urlParser, HtmlImageSourceParser imageSourceParser, IApiRichTextElementParser apiRichTextElementParser, IApiRichTextMarkupParser apiRichTextMarkupParser, IPartialViewBlockEngine partialViewBlockEngine, BlockEditorConverter blockEditorConverter, IJsonSerializer jsonSerializer, - IApiElementBuilder apiElementBuilder, RichTextBlockPropertyValueConstructorCache constructorCache, ILogger logger, + IApiElementBuilder apiElementBuilder, RichTextBlockPropertyValueConstructorCache constructorCache, ILogger logger, IOptionsMonitor deliveryApiSettingsMonitor) { - _umbracoContextAccessor = umbracoContextAccessor; - _macroRenderer = macroRenderer; _linkParser = linkParser; _urlParser = urlParser; _imageSourceParser = imageSourceParser; @@ -113,8 +64,8 @@ public class RteMacroRenderingValueConverter : SimpleTinyMceValueConverter, IDel public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType) => - // because that version of RTE converter parses {locallink} and executes macros, its value has - // to be cached at the published snapshot level, because we have no idea what the macros may depend on actually. + // because that version of RTE converter parses {locallink} and renders blocks, its value has + // to be cached at the published snapshot level, because we have no idea what the block renderings may depend on actually. PropertyCacheLevel.Snapshot; // to counterweigh the cache level, we're going to do as much of the heavy lifting as we can while converting source to intermediate @@ -170,35 +121,6 @@ public class RteMacroRenderingValueConverter : SimpleTinyMceValueConverter, IDel : _apiRichTextElementParser.Parse(richTextEditorIntermediateValue.Markup, richTextEditorIntermediateValue.RichTextBlockModel); } - // NOT thread-safe over a request because it modifies the - // global UmbracoContext.Current.InPreviewMode status. So it - // should never execute in // over the same UmbracoContext with - // different preview modes. - private string RenderRteMacros(string source, bool preview) - { - IUmbracoContext umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); - using (umbracoContext.ForcedPreview(preview)) // force for macro rendering - { - var sb = new StringBuilder(); - - MacroTagParser.ParseMacros( - source, - - // callback for when text block is found - textBlock => sb.Append(textBlock), - - // callback for when macro syntax is found - (macroAlias, macroAttributes) => sb.Append(_macroRenderer.RenderAsync( - macroAlias, - umbracoContext.PublishedRequest?.PublishedContent, - - // needs to be explicitly casted to Dictionary - macroAttributes.ConvertTo(x => (string)x, x => x)!).GetAwaiter().GetResult().Text)); - - return sb.ToString(); - } - } - private string? Convert(object? source, bool preview) { if (source is not IRichTextEditorIntermediateValue intermediateValue) @@ -213,9 +135,6 @@ public class RteMacroRenderingValueConverter : SimpleTinyMceValueConverter, IDel sourceString = _urlParser.EnsureUrls(sourceString); sourceString = _imageSourceParser.EnsureImageSources(sourceString); - // ensure string is parsed for macros and macros are executed correctly - sourceString = RenderRteMacros(sourceString, preview); - // render blocks sourceString = RenderRichTextBlockModel(sourceString, intermediateValue.RichTextBlockModel); diff --git a/src/Umbraco.Infrastructure/Telemetry/Providers/MacroTelemetryProvider.cs b/src/Umbraco.Infrastructure/Telemetry/Providers/MacroTelemetryProvider.cs deleted file mode 100644 index 12309dd2f1..0000000000 --- a/src/Umbraco.Infrastructure/Telemetry/Providers/MacroTelemetryProvider.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Umbraco.Cms.Core; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Services; -using Umbraco.Cms.Infrastructure.Telemetry.Interfaces; - -namespace Umbraco.Cms.Infrastructure.Telemetry.Providers; - -public class MacroTelemetryProvider : IDetailedTelemetryProvider -{ - private readonly IMacroService _macroService; - - public MacroTelemetryProvider(IMacroService macroService) => _macroService = macroService; - - public IEnumerable GetInformation() - { - var macros = _macroService.GetAll().Count(); - yield return new UsageInformation(Constants.Telemetry.MacroCount, macros); - } -} diff --git a/src/Umbraco.Infrastructure/Templates/PartialViews/PartialViewPopulator.cs b/src/Umbraco.Infrastructure/Templates/PartialViews/PartialViewPopulator.cs index 4cc8e038c6..2651a09eab 100644 --- a/src/Umbraco.Infrastructure/Templates/PartialViews/PartialViewPopulator.cs +++ b/src/Umbraco.Infrastructure/Templates/PartialViews/PartialViewPopulator.cs @@ -32,7 +32,7 @@ internal sealed class PartialViewPopulator : IPartialViewPopulator IPartialView? existingView = _fileService.GetPartialView(fileSystemPath); if (existingView is null) { - var view = new PartialView(PartialViewType.PartialView, fileSystemPath) + var view = new PartialView(fileSystemPath) { Content = GetTextFromStream(content) }; diff --git a/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj b/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj index 2debba53c9..f1f51237a7 100644 --- a/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj +++ b/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj @@ -66,4 +66,8 @@ <_Parameter1>Umbraco.Cms.Infrastructure + + + + diff --git a/src/Umbraco.Web.Common/Authorization/AuthorizationPolicies.cs b/src/Umbraco.Web.Common/Authorization/AuthorizationPolicies.cs index 3659b45b12..b3cb194a11 100644 --- a/src/Umbraco.Web.Common/Authorization/AuthorizationPolicies.cs +++ b/src/Umbraco.Web.Common/Authorization/AuthorizationPolicies.cs @@ -48,7 +48,6 @@ public static class AuthorizationPolicies public const string TreeAccessDocuments = nameof(TreeAccessDocuments); public const string TreeAccessUsers = nameof(TreeAccessUsers); public const string TreeAccessPartialViews = nameof(TreeAccessPartialViews); - public const string TreeAccessPartialViewMacros = nameof(TreeAccessPartialViewMacros); public const string TreeAccessDataTypes = nameof(TreeAccessDataTypes); public const string TreeAccessPackages = nameof(TreeAccessPackages); public const string TreeAccessLogs = nameof(TreeAccessLogs); @@ -57,7 +56,6 @@ public static class AuthorizationPolicies public const string TreeAccessDictionary = nameof(TreeAccessDictionary); public const string TreeAccessRelationTypes = nameof(TreeAccessRelationTypes); public const string TreeAccessMediaTypes = nameof(TreeAccessMediaTypes); - public const string TreeAccessMacros = nameof(TreeAccessMacros); public const string TreeAccessLanguages = nameof(TreeAccessLanguages); public const string TreeAccessMemberGroups = nameof(TreeAccessMemberGroups); public const string TreeAccessDocumentTypes = nameof(TreeAccessDocumentTypes); diff --git a/src/Umbraco.Web.Common/DependencyInjection/UmbracoBuilderExtensions.cs b/src/Umbraco.Web.Common/DependencyInjection/UmbracoBuilderExtensions.cs index 8b322a509d..77935ee95d 100644 --- a/src/Umbraco.Web.Common/DependencyInjection/UmbracoBuilderExtensions.cs +++ b/src/Umbraco.Web.Common/DependencyInjection/UmbracoBuilderExtensions.cs @@ -26,7 +26,6 @@ using Umbraco.Cms.Core.Extensions; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Logging; -using Umbraco.Cms.Core.Macros; using Umbraco.Cms.Core.Net; using Umbraco.Cms.Core.Notifications; using Umbraco.Cms.Core.Persistence.Repositories; @@ -51,7 +50,6 @@ using Umbraco.Cms.Web.Common.Controllers; using Umbraco.Cms.Web.Common.DependencyInjection; using Umbraco.Cms.Web.Common.FileProviders; using Umbraco.Cms.Web.Common.Localization; -using Umbraco.Cms.Web.Common.Macros; using Umbraco.Cms.Web.Common.Middleware; using Umbraco.Cms.Web.Common.ModelBinders; using Umbraco.Cms.Web.Common.Mvc; @@ -287,25 +285,6 @@ public static partial class UmbracoBuilderExtensions builder.Services.AddUnique(); - builder.Services.AddUnique(serviceProvider => - { - return new MacroRenderer( - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService>(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService>(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService()); - }); - - builder.Services.AddSingleton(); builder.Services.AddSingleton(); // register the umbraco context factory diff --git a/src/Umbraco.Web.Common/Filters/EnsurePartialViewMacroViewContextFilterAttribute.cs b/src/Umbraco.Web.Common/Filters/EnsurePartialViewMacroViewContextFilterAttribute.cs deleted file mode 100644 index b6ca40efc2..0000000000 --- a/src/Umbraco.Web.Common/Filters/EnsurePartialViewMacroViewContextFilterAttribute.cs +++ /dev/null @@ -1,92 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Mvc.Rendering; -using Microsoft.AspNetCore.Mvc.ViewEngines; -using Microsoft.AspNetCore.Mvc.ViewFeatures; -using Umbraco.Cms.Web.Common.Constants; -using Umbraco.Cms.Web.Common.Controllers; - -namespace Umbraco.Cms.Web.Common.Filters; - -/// -/// This is a special filter which is required for the RTE to be able to render Partial View Macros that -/// contain forms when the RTE value is resolved outside of an MVC view being rendered -/// -/// -/// The entire way that we support partial view macros that contain forms isn't really great, these forms -/// need to be executed as ChildActions so that the ModelState,ViewData,TempData get merged into that action -/// so the form can show errors, viewdata, etc... -/// Under normal circumstances, macros will be rendered after a ViewContext is created but in some cases -/// developers will resolve the RTE value in the controller, in this case the Form won't be rendered correctly -/// with merged ModelState from the controller because the special DataToken hasn't been set yet (which is -/// normally done in the UmbracoViewPageOfModel when a real ViewContext is available. -/// So we need to detect if the currently rendering controller is IRenderController and if so we'll ensure that -/// this DataToken exists before the action executes in case the developer resolves an RTE value that contains -/// a partial view macro form. -/// -public class EnsurePartialViewMacroViewContextFilterAttribute : ActionFilterAttribute -{ - /// - /// Ensures the custom ViewContext datatoken is set before the RenderController action is invoked, - /// this ensures that any calls to GetPropertyValue with regards to RTE or Grid editors can still - /// render any PartialViewMacro with a form and maintain ModelState - /// - public override void OnActionExecuting(ActionExecutingContext context) - { - if (!(context.Controller is Controller controller)) - { - return; - } - - // ignore anything that is not IRenderController - if (!(controller is IRenderController)) - { - return; - } - - SetViewContext(context, controller); - } - - /// - /// Ensures that the custom ViewContext datatoken is set after the RenderController action is invoked, - /// this ensures that any custom ModelState that may have been added in the RenderController itself is - /// passed onwards in case it is required when rendering a PartialViewMacro with a form - /// - /// The filter context. - public override void OnResultExecuting(ResultExecutingContext context) - { - if (!(context.Controller is Controller controller)) - { - return; - } - - // ignore anything that is not IRenderController - if (!(controller is IRenderController)) - { - return; - } - - SetViewContext(context, controller); - } - - private void SetViewContext(ActionContext context, Controller controller) - { - var viewCtx = new ViewContext( - context, - new DummyView(), - controller.ViewData, - controller.TempData, - new StringWriter(), - new HtmlHelperOptions()); - - // set the special data token - context.RouteData.DataTokens[ViewConstants.DataTokenCurrentViewContext] = viewCtx; - } - - private class DummyView : IView - { - public string Path { get; } = null!; - - public Task RenderAsync(ViewContext context) => Task.CompletedTask; - } -} diff --git a/src/Umbraco.Web.Common/Macros/MacroRenderer.cs b/src/Umbraco.Web.Common/Macros/MacroRenderer.cs deleted file mode 100644 index 1bc46f0db0..0000000000 --- a/src/Umbraco.Web.Common/Macros/MacroRenderer.cs +++ /dev/null @@ -1,516 +0,0 @@ -using System.Text; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Umbraco.Cms.Core; -using Umbraco.Cms.Core.Cache; -using Umbraco.Cms.Core.Configuration.Models; -using Umbraco.Cms.Core.DependencyInjection; -using Umbraco.Cms.Core.Events; -using Umbraco.Cms.Core.Extensions; -using Umbraco.Cms.Core.Logging; -using Umbraco.Cms.Core.Macros; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Models.PublishedContent; -using Umbraco.Cms.Core.Security; -using Umbraco.Cms.Core.Services; -using Umbraco.Cms.Core.Web; -using Umbraco.Extensions; -using IHostingEnvironment = Umbraco.Cms.Core.Hosting.IHostingEnvironment; - -namespace Umbraco.Cms.Web.Common.Macros; - -public class MacroRenderer : IMacroRenderer -{ - private readonly AppCaches _appCaches; - private readonly ICookieManager _cookieManager; - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IWebHostEnvironment _webHostEnvironment; - private readonly ILogger _logger; - private readonly IMacroService _macroService; - private readonly PartialViewMacroEngine _partialViewMacroEngine; - private readonly IProfilingLogger _profilingLogger; - private readonly IRequestAccessor _requestAccessor; - private readonly ISessionManager _sessionManager; - private readonly ILocalizedTextService _textService; - private readonly IUmbracoContextAccessor _umbracoContextAccessor; - private ContentSettings _contentSettings; - - [Obsolete("Please use constructor that takes an IWebHostEnvironment instead")] - public MacroRenderer( - IProfilingLogger profilingLogger, - ILogger logger, - IUmbracoContextAccessor umbracoContextAccessor, - IOptionsMonitor contentSettings, - ILocalizedTextService textService, - AppCaches appCaches, - IMacroService macroService, - IHostingEnvironment hostingEnvironment, - ICookieManager cookieManager, - ISessionManager sessionManager, - IRequestAccessor requestAccessor, - PartialViewMacroEngine partialViewMacroEngine, - IHttpContextAccessor httpContextAccessor) - : this( - profilingLogger, - logger, - umbracoContextAccessor, - contentSettings, - textService, - appCaches, - macroService, - cookieManager, - sessionManager, - requestAccessor, - partialViewMacroEngine, - httpContextAccessor, - StaticServiceProvider.Instance.GetRequiredService()) - { - } - - public MacroRenderer( - IProfilingLogger profilingLogger, - ILogger logger, - IUmbracoContextAccessor umbracoContextAccessor, - IOptionsMonitor contentSettings, - ILocalizedTextService textService, - AppCaches appCaches, - IMacroService macroService, - ICookieManager cookieManager, - ISessionManager sessionManager, - IRequestAccessor requestAccessor, - PartialViewMacroEngine partialViewMacroEngine, - IHttpContextAccessor httpContextAccessor, - IWebHostEnvironment webHostEnvironment) - { - _profilingLogger = profilingLogger ?? throw new ArgumentNullException(nameof(profilingLogger)); - _logger = logger; - _umbracoContextAccessor = - umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor)); - _contentSettings = contentSettings.CurrentValue ?? throw new ArgumentNullException(nameof(contentSettings)); - _textService = textService; - _appCaches = appCaches ?? throw new ArgumentNullException(nameof(appCaches)); - _macroService = macroService ?? throw new ArgumentNullException(nameof(macroService)); - _cookieManager = cookieManager; - _sessionManager = sessionManager; - _requestAccessor = requestAccessor; - _partialViewMacroEngine = partialViewMacroEngine; - _httpContextAccessor = httpContextAccessor; - _webHostEnvironment = webHostEnvironment; - - contentSettings.OnChange(x => _contentSettings = x); - } - - #region Execution helpers - - // parses attribute value looking for [@requestKey], [%sessionKey] - // supports fallbacks eg "[@requestKey],[%sessionKey],1234" - private string? ParseAttribute(string? attributeValue) - { - if (attributeValue is null) - { - return attributeValue; - } - - // check for potential querystring/cookie variables - attributeValue = attributeValue.Trim(); - if (attributeValue.StartsWith("[") == false) - { - return attributeValue; - } - - var tokens = attributeValue.Split(Core.Constants.CharArrays.Comma).Select(x => x.Trim()).ToArray(); - - // ensure we only process valid input ie each token must be [?x] and not eg a json array - // like [1,2,3] which we don't want to parse - however the last one can be a literal, so - // don't check on the last one which can be just anything - check all previous tokens - char[] validTypes = { '@', '%' }; - if (tokens.Take(tokens.Length - 1).Any(x => - x.Length < 4 // ie "[?x]".Length - too short - || x[0] != '[' // starts with [ - || x[x.Length - 1] != ']' // ends with ] - || validTypes.Contains(x[1]) == false)) - { - return attributeValue; - } - - foreach (var token in tokens) - { - var isToken = token.Length > 4 && token[0] == '[' && token[token.Length - 1] == ']' && - validTypes.Contains(token[1]); - - if (isToken == false) - { - // anything that is not a token is a value, use it - attributeValue = token; - break; - } - - var type = token[1]; - var name = token.Substring(2, token.Length - 3); - - switch (type) - { - case '@': - attributeValue = _requestAccessor.GetRequestValue(name); - break; - case '%': - attributeValue = _sessionManager.GetSessionValue(name); - if (string.IsNullOrEmpty(attributeValue)) - { - attributeValue = _cookieManager.GetCookieValue(name); - } - - break; - } - - attributeValue = attributeValue?.Trim(); - if (string.IsNullOrEmpty(attributeValue) == false) - { - break; // got a value, use it - } - } - - return attributeValue; - } - - #endregion - - #region MacroContent cache - - // gets this macro content cache identifier - private async Task GetContentCacheIdentifier(MacroModel model, int pageId, string cultureName) - { - var id = new StringBuilder(); - - var alias = model.Alias; - id.AppendFormat("{0}-", alias); - - // always add current culture to the key to allow variants to have different cache results - if (!string.IsNullOrEmpty(cultureName)) - { - // are there any unusual culture formats we'd need to handle? - id.AppendFormat("{0}-", cultureName); - } - - if (model.CacheByPage) - { - id.AppendFormat("{0}-", pageId); - } - - if (model.CacheByMember) - { - object key = 0; - - if (_httpContextAccessor.HttpContext?.User.Identity?.IsAuthenticated ?? false) - { - IMemberManager memberManager = - _httpContextAccessor.HttpContext.RequestServices.GetRequiredService(); - MemberIdentityUser? member = await memberManager.GetCurrentMemberAsync(); - if (member is not null) - { - key = member.Key; - } - } - - id.AppendFormat("m{0}-", key); - } - - foreach (var value in model.Properties.Select(x => x.Value)) - { - id.AppendFormat("{0}-", value?.Length <= 255 ? value : value?.Substring(0, 255)); - } - - return id.ToString(); - } - - // gets this macro content from the cache - // ensuring that it is appropriate to use the cache - private MacroContent? GetMacroContentFromCache(MacroModel model) - { - if (!_umbracoContextAccessor.TryGetUmbracoContext(out IUmbracoContext? umbracoContext)) - { - return null; - } - - // only if cache is enabled - if (umbracoContext.InPreviewMode || model.CacheDuration <= 0) - { - return null; - } - - IAppPolicyCache cache = _appCaches.RuntimeCache; - MacroContent? macroContent = - cache.GetCacheItem(CacheKeys.MacroContentCacheKey + model.CacheIdentifier); - - if (macroContent == null) - { - return null; - } - if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) - { - _logger.LogDebug("Macro content loaded from cache '{MacroCacheId}'", model.CacheIdentifier); - } - // ensure that the source has not changed - // note: does not handle dependencies, and never has - FileInfo? macroSource = GetMacroFile(model); // null if macro is not file-based - if (macroSource != null) - { - if (macroSource.Exists == false) - { - if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) - { - _logger.LogDebug("Macro source does not exist anymore, ignore cache."); - } - return null; - } - - if (macroContent.Date < macroSource.LastWriteTime) - { - if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) - { - _logger.LogDebug("Macro source has changed, ignore cache."); - } - return null; - } - } - - return macroContent; - } - - // stores macro content into the cache - private async Task AddMacroContentToCacheAsync(MacroModel model, MacroContent macroContent) - { - IUmbracoContext umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); - - // only if cache is enabled - if (umbracoContext.InPreviewMode || model.CacheDuration <= 0) - { - return; - } - - // do not cache if it should cache by member and there's not member - if (model.CacheByMember) - { - IMemberManager? memberManager = - _httpContextAccessor.HttpContext?.RequestServices.GetRequiredService(); - MemberIdentityUser? member = await memberManager?.GetCurrentMemberAsync()!; - if (member is null) - { - return; - } - } - - // remember when we cache the content - macroContent.Date = DateTime.Now; - - IAppPolicyCache cache = _appCaches.RuntimeCache; - cache.Insert( - CacheKeys.MacroContentCacheKey + model.CacheIdentifier, - () => macroContent, - new TimeSpan(0, 0, model.CacheDuration)); - if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) - { - _logger.LogDebug("Macro content saved to cache '{MacroCacheId}'", model.CacheIdentifier); - } - } - - // gets the macro source file name - // null if the macro is not file-based, or not supported - internal static string? GetMacroFileName(MacroModel model) - { - var filename = model.MacroSource; // partial views are saved with their full virtual path - - return string.IsNullOrEmpty(filename) ? null : filename; - } - - // gets the macro source file - // null if macro is not file-based - private FileInfo? GetMacroFile(MacroModel model) - { - var filename = GetMacroFileName(model); - if (filename == null) - { - return null; - } - - var mapped = _webHostEnvironment.MapPathContentRoot(filename); - - var file = new FileInfo(mapped); - return file.Exists ? file : null; - } - - // updates the model properties values according to the attributes - private static void UpdateMacroModelProperties(MacroModel model, IDictionary? macroParams) - { - foreach (MacroPropertyModel prop in model.Properties) - { - var key = prop.Key.ToLowerInvariant(); - prop.Value = macroParams != null && macroParams.ContainsKey(key) - ? macroParams[key]?.ToString() ?? string.Empty - : string.Empty; - } - } - - #endregion - - #region Render/Execute - - public async Task RenderAsync(string macroAlias, IPublishedContent? content, IDictionary? macroParams) - { - IMacro? m = _appCaches.RuntimeCache.GetCacheItem(CacheKeys.MacroFromAliasCacheKey + macroAlias, () => _macroService.GetByAlias(macroAlias)); - - if (m == null) - { - throw new InvalidOperationException("No macro found by alias " + macroAlias); - } - - var macro = new MacroModel(m); - - UpdateMacroModelProperties(macro, macroParams); - return await RenderAsync(macro, content); - } - - private async Task RenderAsync(MacroModel macro, IPublishedContent? content) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - - var macroInfo = $"Render Macro: {macro.Name}, cache: {macro.CacheDuration}"; - using (!_profilingLogger.IsEnabled(Core.Logging.LogLevel.Debug) ? null : _profilingLogger.DebugDuration(macroInfo, "Rendered Macro.")) - { - // parse macro parameters ie replace the special [#key], [$key], etc. syntaxes - foreach (MacroPropertyModel prop in macro.Properties) - { - prop.Value = ParseAttribute(prop.Value); - } - - var cultureName = Thread.CurrentThread.CurrentUICulture.Name; - macro.CacheIdentifier = await GetContentCacheIdentifier(macro, content.Id, cultureName); - - // get the macro from cache if it is there - MacroContent? macroContent = GetMacroContentFromCache(macro); - - // macroContent.IsEmpty may be true, meaning the macro produces no output, - // but still can be cached because its execution did not trigger any error. - // so we need to actually render, only if macroContent is null - if (macroContent != null) - { - return macroContent; - } - - // this will take care of errors - // it may throw, if we actually want to throw, so better not - // catch anything here and let the exception be thrown - Attempt attempt = ExecuteMacroOfType(macro, content); - - // by convention ExecuteMacroByType must either throw or return a result - // just check to avoid internal errors - macroContent = attempt.Result; - if (macroContent == null) - { - throw new Exception("Internal error, ExecuteMacroOfType returned no content."); - } - - // add to cache if render is successful - // content may be empty but that's not an issue - if (attempt.Success) - { - // write to cache (if appropriate) - await AddMacroContentToCacheAsync(macro, macroContent); - } - - return macroContent; - } - } - - /// - /// Executes a macro of a given type. - /// - private Attempt ExecuteMacroWithErrorWrapper(MacroModel macro, string msgIn, string msgOut, Func getMacroContent, Func msgErr) - { - using (!_profilingLogger.IsEnabled(Core.Logging.LogLevel.Debug) ? null : _profilingLogger.DebugDuration(msgIn, msgOut)) - { - return ExecuteProfileMacroWithErrorWrapper(macro, msgIn, getMacroContent, msgErr); - } - } - - /// - /// Executes a macro of a given type. - /// - private Attempt ExecuteProfileMacroWithErrorWrapper(MacroModel macro, string msgIn, Func getMacroContent, Func msgErr) - { - try - { - return Attempt.Succeed(getMacroContent()); - } - catch (Exception e) - { - _logger.LogWarning(e, "Failed {MsgIn}", msgIn); - - var macroErrorEventArgs = new MacroErrorEventArgs - { - Name = macro.Name, - Alias = macro.Alias, - MacroSource = macro.MacroSource, - Exception = e, - Behaviour = _contentSettings.MacroErrors, - }; - - switch (macroErrorEventArgs.Behaviour) - { - case MacroErrorBehaviour.Inline: - // do not throw, eat the exception, display the trace error message - return Attempt.Fail(new MacroContent { Text = msgErr() }, e); - case MacroErrorBehaviour.Silent: - // do not throw, eat the exception, do not display anything - return Attempt.Fail(new MacroContent { Text = string.Empty }, e); - case MacroErrorBehaviour.Content: - // do not throw, eat the exception, display the custom content - return Attempt.Fail(new MacroContent { Text = macroErrorEventArgs.Html ?? string.Empty }, e); - - // case MacroErrorBehaviour.Throw: - default: - // see http://issues.umbraco.org/issue/U4-497 at the end - // throw the original exception - throw; - } - } - } - - /// - /// Executes a macro. - /// - /// - /// Returns an attempt that is successful if the macro ran successfully. If the macro failed - /// to run properly, the attempt fails, though it may contain a content. But for instance that content - /// should not be cached. In that case the attempt may also contain an exception. - /// - private Attempt ExecuteMacroOfType(MacroModel model, IPublishedContent? content) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - // ensure that we are running against a published node (ie available in XML) - // that may not be the case if the macro is embedded in a RTE of an unpublished document - if (content == null) - { - return Attempt.Fail(new MacroContent { Text = "[macro failed (no content)]" }); - } - - return ExecuteMacroWithErrorWrapper( - model, - $"Executing PartialView: MacroSource=\"{model.MacroSource}\".", - "Executed PartialView.", - () => _partialViewMacroEngine.Execute(model, content), - () => _textService.Localize("errors", "macroErrorLoadingPartialView", new[] { model.MacroSource })); - } - - #endregion -} diff --git a/src/Umbraco.Web.Common/Macros/PartialViewMacroEngine.cs b/src/Umbraco.Web.Common/Macros/PartialViewMacroEngine.cs deleted file mode 100644 index 6c3b316841..0000000000 --- a/src/Umbraco.Web.Common/Macros/PartialViewMacroEngine.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System.Text.Encodings.Web; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.AspNetCore.Mvc.Rendering; -using Microsoft.AspNetCore.Mvc.ViewComponents; -using Microsoft.AspNetCore.Mvc.ViewEngines; -using Microsoft.AspNetCore.Mvc.ViewFeatures; -using Microsoft.AspNetCore.Routing; -using Umbraco.Cms.Core.Macros; -using Umbraco.Cms.Core.Models.PublishedContent; -using Umbraco.Cms.Web.Common.Controllers; -using Umbraco.Extensions; - -namespace Umbraco.Cms.Web.Common.Macros; - -/// -/// A macro engine using MVC Partial Views to execute. -/// -public class PartialViewMacroEngine -{ - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IModelMetadataProvider _modelMetadataProvider; - private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory; - - public PartialViewMacroEngine( - IHttpContextAccessor httpContextAccessor, - IModelMetadataProvider modelMetadataProvider, - ITempDataDictionaryFactory tempDataDictionaryFactory) - { - _httpContextAccessor = httpContextAccessor; - _modelMetadataProvider = modelMetadataProvider; - _tempDataDictionaryFactory = tempDataDictionaryFactory; - } - - public MacroContent Execute(MacroModel macro, IPublishedContent content) - { - if (macro == null) - { - throw new ArgumentNullException(nameof(macro)); - } - - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - - if (string.IsNullOrWhiteSpace(macro.MacroSource)) - { - throw new ArgumentException("The MacroSource property of the macro object cannot be null or empty"); - } - - HttpContext httpContext = _httpContextAccessor.GetRequiredHttpContext(); - - RouteData currentRouteData = httpContext.GetRouteData(); - - // Check if there's proxied ViewData (i.e. returned from a SurfaceController) - ProxyViewDataFeature? proxyViewDataFeature = httpContext.Features.Get(); - ViewDataDictionary viewData = proxyViewDataFeature?.ViewData ?? - new ViewDataDictionary(_modelMetadataProvider, new ModelStateDictionary()); - ITempDataDictionary tempData = - proxyViewDataFeature?.TempData ?? _tempDataDictionaryFactory.GetTempData(httpContext); - - var viewContext = new ViewContext( - new ActionContext(httpContext, currentRouteData, new ControllerActionDescriptor()), - new FakeView(), - viewData, - tempData, - TextWriter.Null, - new HtmlHelperOptions()); - - var writer = new StringWriter(); - var viewComponentContext = new ViewComponentContext( - new ViewComponentDescriptor(), - new Dictionary(), - HtmlEncoder.Default, - viewContext, - writer); - - var viewComponent = new PartialViewMacroViewComponent(macro, content, viewComponentContext); - - viewComponent.Invoke().Execute(viewComponentContext); - - var output = writer.GetStringBuilder().ToString(); - - return new MacroContent { Text = output }; - } - - private class FakeView : IView - { - /// - public string Path { get; } = "View"; - - /// - public Task RenderAsync(ViewContext context) => Task.CompletedTask; - } -} diff --git a/src/Umbraco.Web.Common/Macros/PartialViewMacroPage.cs b/src/Umbraco.Web.Common/Macros/PartialViewMacroPage.cs deleted file mode 100644 index 5e8c22f762..0000000000 --- a/src/Umbraco.Web.Common/Macros/PartialViewMacroPage.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Web.Common.Views; - -namespace Umbraco.Cms.Web.Common.Macros; - -/// -/// The base view class that PartialViewMacro views need to inherit from -/// -public abstract class PartialViewMacroPage : UmbracoViewPage -{ -} diff --git a/src/Umbraco.Web.Common/Macros/PartialViewMacroViewComponent.cs b/src/Umbraco.Web.Common/Macros/PartialViewMacroViewComponent.cs deleted file mode 100644 index d0e3b7dbd7..0000000000 --- a/src/Umbraco.Web.Common/Macros/PartialViewMacroViewComponent.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.ViewComponents; -using Umbraco.Cms.Core.Composing; -using Umbraco.Cms.Core.Macros; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Models.PublishedContent; - -namespace Umbraco.Cms.Web.Common.Macros; - -/// -/// Controller to render macro content for Partial View Macros -/// -// [MergeParentContextViewData] // TODO is this requeired now it is a ViewComponent? -[HideFromTypeFinder] // explicitly used: do *not* find and register it! -internal class PartialViewMacroViewComponent : ViewComponent -{ - private readonly IPublishedContent _content; - private readonly MacroModel _macro; - - public PartialViewMacroViewComponent( - MacroModel macro, - IPublishedContent content, - ViewComponentContext viewComponentContext) - { - _macro = macro; - _content = content; - - // This must be set before Invoke is called else the call to View will end up - // using an empty ViewData instance because this hasn't been set yet. - ViewComponentContext = viewComponentContext; - } - - public IViewComponentResult Invoke() - { - var model = new PartialViewMacroModel( - _content, - _macro.Id, - _macro.Alias, - _macro.Name, - _macro.Properties.ToDictionary(x => x.Key, x => (object?)x.Value)); - - ViewViewComponentResult result = View(_macro.MacroSource, model); - - return result; - } -} diff --git a/src/Umbraco.Web.Common/Mvc/UmbracoMvcConfigureOptions.cs b/src/Umbraco.Web.Common/Mvc/UmbracoMvcConfigureOptions.cs index 83a2e28834..af7f85a221 100644 --- a/src/Umbraco.Web.Common/Mvc/UmbracoMvcConfigureOptions.cs +++ b/src/Umbraco.Web.Common/Mvc/UmbracoMvcConfigureOptions.cs @@ -36,7 +36,6 @@ public class UmbracoMvcConfigureOptions : IConfigureOptions options.ModelBinderProviders.Insert(0, new ContentModelBinderProvider()); options.ModelValidatorProviders.Insert(0, new BypassRenderingModelValidatorProvider()); options.ModelMetadataDetailsProviders.Add(new BypassRenderingModelValidationMetadataProvider()); - options.Filters.Insert(0, new EnsurePartialViewMacroViewContextFilterAttribute()); // these MVC options may be applied more than once; let's make sure we only add these conventions once. if (options.Conventions.Any(convention => convention is UmbracoBackofficeToken) is false) diff --git a/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs b/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs index f8c41879ac..fe71e62f1f 100644 --- a/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs +++ b/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs @@ -164,7 +164,7 @@ _cleanedUmbracoUrl ??= _uriUtility.UriToUmbraco(OriginalRequestUrl); /// public IDisposable ForcedPreview(bool preview) { - // say we render a macro or RTE in a give 'preview' mode that might not be the 'current' one, + // say we render an RTE in a give 'preview' mode that might not be the 'current' one, // then due to the way it all works at the moment, the 'current' published snapshot need to be in the proper // default 'preview' mode - somehow we have to force it. and that could be recursive. InPreviewMode = preview; diff --git a/src/Umbraco.Web.Common/UmbracoHelper.cs b/src/Umbraco.Web.Common/UmbracoHelper.cs index e59e4db588..f441d3eabd 100644 --- a/src/Umbraco.Web.Common/UmbracoHelper.cs +++ b/src/Umbraco.Web.Common/UmbracoHelper.cs @@ -1,13 +1,11 @@ using System.Globalization; using System.Xml.XPath; -using Serilog.Events; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Dictionary; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Core.Templates; using Umbraco.Cms.Core.Xml; -using Umbraco.Extensions; namespace Umbraco.Cms.Web.Common; @@ -102,36 +100,6 @@ public class UmbracoHelper public async Task RenderTemplateAsync(int contentId, int? altTemplateId = null) => await _componentRenderer.RenderTemplateAsync(contentId, altTemplateId); - #region RenderMacro - - /// - /// Renders the macro with the specified alias. - /// - /// The alias. - /// - public async Task RenderMacroAsync(string alias) - => await _componentRenderer.RenderMacroAsync(AssignedContentItem.Id, alias, null); - - /// - /// Renders the macro with the specified alias, passing in the specified parameters. - /// - /// The alias. - /// The parameters. - /// - public async Task RenderMacroAsync(string alias, object parameters) - => await _componentRenderer.RenderMacroAsync(AssignedContentItem.Id, alias, parameters.ToDictionary()); - - /// - /// Renders the macro with the specified alias, passing in the specified parameters. - /// - /// The alias. - /// The parameters. - /// - public async Task RenderMacroAsync(string alias, IDictionary parameters) - => await _componentRenderer.RenderMacroAsync(AssignedContentItem.Id, alias, parameters); - - #endregion - #region Dictionary /// diff --git a/src/Umbraco.Web.Website/Controllers/UmbExternalLoginController.cs b/src/Umbraco.Web.Website/Controllers/UmbExternalLoginController.cs index 2cbda678de..432761a197 100644 --- a/src/Umbraco.Web.Website/Controllers/UmbExternalLoginController.cs +++ b/src/Umbraco.Web.Website/Controllers/UmbExternalLoginController.cs @@ -59,7 +59,7 @@ public class UmbExternalLoginController : SurfaceController } /// - /// Endpoint used to redirect to a specific login provider. This endpoint is used from the Login Macro snippet. + /// Endpoint used to redirect to a specific login provider. This endpoint is used from the Login snippet. /// [HttpPost] [AllowAnonymous] diff --git a/src/Umbraco.Web.Website/ViewEngines/PluginRazorViewEngineOptionsSetup.cs b/src/Umbraco.Web.Website/ViewEngines/PluginRazorViewEngineOptionsSetup.cs index b298b5d8ec..ca7696c1e9 100644 --- a/src/Umbraco.Web.Website/ViewEngines/PluginRazorViewEngineOptionsSetup.cs +++ b/src/Umbraco.Web.Website/ViewEngines/PluginRazorViewEngineOptionsSetup.cs @@ -34,9 +34,8 @@ public class PluginRazorViewEngineOptionsSetup : IConfigureOptions, - IWithIdBuilder, - IWithKeyBuilder, - IWithAliasBuilder, - IWithNameBuilder -{ - private readonly List _propertyBuilders = new(); - private string _alias; - private bool? _cacheByMember; - private bool? _cacheByPage; - private int? _cacheDuration; - private bool? _dontRender; - - private int? _id; - private Guid? _key; - private string _macroSource; - private string _name; - private bool? _useInEditor; - - string IWithAliasBuilder.Alias - { - get => _alias; - set => _alias = value; - } - - int? IWithIdBuilder.Id - { - get => _id; - set => _id = value; - } - - Guid? IWithKeyBuilder.Key - { - get => _key; - set => _key = value; - } - - string IWithNameBuilder.Name - { - get => _name; - set => _name = value; - } - - public MacroBuilder WithUseInEditor(bool useInEditor) - { - _useInEditor = useInEditor; - return this; - } - - public MacroBuilder WithCacheDuration(int cacheDuration) - { - _cacheDuration = cacheDuration; - return this; - } - - public MacroBuilder WithCacheByPage(bool cacheByPage) - { - _cacheByPage = cacheByPage; - return this; - } - - public MacroBuilder WithCacheByMember(bool cacheByMember) - { - _cacheByMember = cacheByMember; - return this; - } - - public MacroBuilder WithDontRender(bool dontRender) - { - _dontRender = dontRender; - return this; - } - - public MacroBuilder WithSource(string macroSource) - { - _macroSource = macroSource; - return this; - } - - public MacroPropertyBuilder AddProperty() - { - var builder = new MacroPropertyBuilder(this); - - _propertyBuilders.Add(builder); - - return builder; - } - - public override Macro Build() - { - var id = _id ?? 1; - var name = _name ?? Guid.NewGuid().ToString(); - var alias = _alias ?? name.ToCamelCase(); - var key = _key ?? Guid.NewGuid(); - var useInEditor = _useInEditor ?? false; - var cacheDuration = _cacheDuration ?? 0; - var cacheByPage = _cacheByPage ?? false; - var cacheByMember = _cacheByMember ?? false; - var dontRender = _dontRender ?? false; - var macroSource = _macroSource ?? string.Empty; - - var shortStringHelper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig()); - - var macro = new Macro(shortStringHelper, id, key, useInEditor, cacheDuration, alias, name, cacheByPage, cacheByMember, dontRender, macroSource); - - foreach (var property in _propertyBuilders.Select(x => x.Build())) - { - macro.Properties.Add(property); - } - - return macro; - } -} diff --git a/tests/Umbraco.Tests.Common/Builders/MacroPropertyBuilder.cs b/tests/Umbraco.Tests.Common/Builders/MacroPropertyBuilder.cs deleted file mode 100644 index ff181cf689..0000000000 --- a/tests/Umbraco.Tests.Common/Builders/MacroPropertyBuilder.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Umbraco. -// See LICENSE for more details. - -using System; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Tests.Common.Builders.Extensions; -using Umbraco.Cms.Tests.Common.Builders.Interfaces; - -namespace Umbraco.Cms.Tests.Common.Builders; - -public class MacroPropertyBuilder - : ChildBuilderBase, - IWithIdBuilder, - IWithKeyBuilder, - IWithAliasBuilder, - IWithNameBuilder, - IWithSortOrderBuilder -{ - private string _alias; - private string _editorAlias; - private int? _id; - private Guid? _key; - private string _name; - private int? _sortOrder; - - public MacroPropertyBuilder(MacroBuilder parentBuilder) - : base(parentBuilder) - { - } - - string IWithAliasBuilder.Alias - { - get => _alias; - set => _alias = value; - } - - int? IWithIdBuilder.Id - { - get => _id; - set => _id = value; - } - - Guid? IWithKeyBuilder.Key - { - get => _key; - set => _key = value; - } - - string IWithNameBuilder.Name - { - get => _name; - set => _name = value; - } - - int? IWithSortOrderBuilder.SortOrder - { - get => _sortOrder; - set => _sortOrder = value; - } - - public MacroPropertyBuilder WithEditorAlias(string editorAlias) - { - _editorAlias = editorAlias; - return this; - } - - public override IMacroProperty Build() - { - var id = _id ?? 1; - var name = _name ?? Guid.NewGuid().ToString(); - var alias = _alias ?? name.ToCamelCase(); - var key = _key ?? Guid.NewGuid(); - var sortOrder = _sortOrder ?? 0; - var editorAlias = _editorAlias ?? string.Empty; - - return new MacroProperty(id, key, alias, name, sortOrder, editorAlias); - } -} diff --git a/tests/Umbraco.Tests.Common/Builders/PartialViewBuilder.cs b/tests/Umbraco.Tests.Common/Builders/PartialViewBuilder.cs index ead5a4f189..a7a6f53e54 100644 --- a/tests/Umbraco.Tests.Common/Builders/PartialViewBuilder.cs +++ b/tests/Umbraco.Tests.Common/Builders/PartialViewBuilder.cs @@ -10,7 +10,6 @@ public class PartialViewBuilder { private string _path; private string _content; - private PartialViewType _viewType = PartialViewType.Unknown; public PartialViewBuilder WithPath(string path) { @@ -24,18 +23,11 @@ public class PartialViewBuilder return this; } - public PartialViewBuilder WithViewType(PartialViewType viewType) - { - _viewType = viewType; - return this; - } - public override IPartialView Build() { var path = _path ?? string.Empty; var content = _content ?? string.Empty; - var viewType = _viewType; - return new PartialView(viewType, path) { Content = content }; + return new PartialView(path) { Content = content }; } } diff --git a/tests/Umbraco.Tests.Common/TestHelpers/FileSystemsCreator.cs b/tests/Umbraco.Tests.Common/TestHelpers/FileSystemsCreator.cs index b813f70015..7c34001689 100644 --- a/tests/Umbraco.Tests.Common/TestHelpers/FileSystemsCreator.cs +++ b/tests/Umbraco.Tests.Common/TestHelpers/FileSystemsCreator.cs @@ -15,7 +15,6 @@ public static class FileSystemsCreator /// /// /// - /// /// /// /// @@ -26,10 +25,9 @@ public static class FileSystemsCreator IIOHelper ioHelper, IOptions globalSettings, IHostingEnvironment hostingEnvironment, - IFileSystem macroPartialFileSystem, IFileSystem partialViewsFileSystem, IFileSystem stylesheetFileSystem, IFileSystem scriptsFileSystem, IFileSystem mvcViewFileSystem) => - new(loggerFactory, ioHelper, globalSettings, hostingEnvironment, macroPartialFileSystem, partialViewsFileSystem, stylesheetFileSystem, scriptsFileSystem, mvcViewFileSystem); + new(loggerFactory, ioHelper, globalSettings, hostingEnvironment, partialViewsFileSystem, stylesheetFileSystem, scriptsFileSystem, mvcViewFileSystem); } diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs index e417dc2494..3031a6e6a1 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Packaging/CreatedPackagesRepositoryTests.cs @@ -45,8 +45,6 @@ public class CreatedPackagesRepositoryTests : UmbracoIntegrationTest private IFileService FileService => GetRequiredService(); - private IMacroService MacroService => GetRequiredService(); - private IDictionaryItemService DictionaryItemService => GetRequiredService(); private ILocalizationService LocalizationService => GetRequiredService(); @@ -68,7 +66,6 @@ public class CreatedPackagesRepositoryTests : UmbracoIntegrationTest ContentTypeService, DataTypeService, FileService, - MacroService, LocalizationService, HostingEnvironment, EntityXmlSerializer, @@ -158,7 +155,6 @@ public class CreatedPackagesRepositoryTests : UmbracoIntegrationTest Assert.AreEqual(0, def.DataTypes.Count()); Assert.AreEqual(0, def.DictionaryItems.Count()); Assert.AreEqual(0, def.DocumentTypes.Count()); - Assert.AreEqual(0, def.Macros.Count()); Assert.AreEqual(0, def.MediaTypes.Count()); Assert.AreEqual(0, def.MediaUdis.Count()); Assert.AreEqual(0, def.PartialViews.Count()); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/TelemetryProviderTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/TelemetryProviderTests.cs index 2f3e47e08b..306b2c58a0 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/TelemetryProviderTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Services/TelemetryProviderTests.cs @@ -1,21 +1,13 @@ // Copyright (c) Umbraco. // See LICENSE for more details. -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Moq; using NUnit.Framework; using Umbraco.Cms.Core; -using Umbraco.Cms.Core.Cache; -using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.ContentEditing; using Umbraco.Cms.Core.Models.Membership; using Umbraco.Cms.Core.Services; -using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement; -using Umbraco.Cms.Infrastructure.Scoping; using Umbraco.Cms.Infrastructure.Telemetry.Providers; using Umbraco.Cms.Tests.Common.Builders; using Umbraco.Cms.Tests.Common.Builders.Extensions; @@ -47,8 +39,6 @@ public class TelemetryProviderTests : UmbracoIntegrationTest private UserTelemetryProvider UserTelemetryProvider => GetRequiredService(); - private MacroTelemetryProvider MacroTelemetryProvider => GetRequiredService(); - private MediaTelemetryProvider MediaTelemetryProvider => GetRequiredService(); private PropertyEditorTelemetryProvider PropertyEditorTelemetryProvider => @@ -76,7 +66,6 @@ public class TelemetryProviderTests : UmbracoIntegrationTest builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); - builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); base.CustomTestSetup(builder); @@ -159,15 +148,6 @@ public class TelemetryProviderTests : UmbracoIntegrationTest Assert.AreEqual(3, result.First().Data); } - [Test] - public void MacroTelemetry_Can_Get_Macros() - { - BuildMacros(); - var result = MacroTelemetryProvider.GetInformation() - .FirstOrDefault(x => x.Name == Constants.Telemetry.MacroCount); - Assert.AreEqual(3, result.Data); - } - [Test] public void MediaTelemetry_Can_Get_Media_In_Folders() { @@ -344,20 +324,6 @@ public class TelemetryProviderTests : UmbracoIntegrationTest } } - private void BuildMacros() - { - var scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) - { - var repository = new MacroRepository((IScopeAccessor)scopeProvider, AppCaches.Disabled, Mock.Of>(), ShortStringHelper); - - repository.Save(new Macro(ShortStringHelper, "test1", "Test1", "~/views/macropartials/test1.cshtml")); - repository.Save(new Macro(ShortStringHelper, "test2", "Test2", "~/views/macropartials/test2.cshtml")); - repository.Save(new Macro(ShortStringHelper, "test3", "Tet3", "~/views/macropartials/test3.cshtml")); - scope.Complete(); - } - } - private void AddPropType(string alias, int dataTypeId, IContentType ct) { var contentCollection = new PropertyTypeCollection(true) diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Core/Telemetry/TelemetryServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Core/Telemetry/TelemetryServiceTests.cs index c92416402f..03c4fd8633 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Core/Telemetry/TelemetryServiceTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Core/Telemetry/TelemetryServiceTests.cs @@ -31,7 +31,6 @@ public class TelemetryServiceTests : UmbracoIntegrationTest Constants.Telemetry.DomainCount, Constants.Telemetry.ExamineIndexCount, Constants.Telemetry.LanguageCount, - Constants.Telemetry.MacroCount, Constants.Telemetry.MediaCount, Constants.Telemetry.MediaCount, Constants.Telemetry.TemplateCount, diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Packaging/PackageDataInstallationTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Packaging/PackageDataInstallationTests.cs index ac40f6d5a3..5fe47f4d47 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Packaging/PackageDataInstallationTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Packaging/PackageDataInstallationTests.cs @@ -29,8 +29,6 @@ public class PackageDataInstallationTests : UmbracoIntegrationTestWithContent private IDictionaryItemService DictionaryItemService => GetRequiredService(); - private IMacroService MacroService => GetRequiredService(); - [HideFromTypeFinder] [DataEditor("7e062c13-7c41-4ad9-b389-41d88aeef87c")] public class Editor1 : DataEditor @@ -694,53 +692,6 @@ public class PackageDataInstallationTests : UmbracoIntegrationTestWithContent } } - [Test] - public void Can_Import_Macros() - { - // Arrange - var strXml = ImportResources.uBlogsy_Package; - var xml = XElement.Parse(strXml); - var macrosElement = xml.Descendants("Macros").First(); - - // Act - var macros = PackageDataInstallation.ImportMacros( - macrosElement.Elements("macro"), - -1).ToList(); - - // Assert - Assert.That(macros.Any(), Is.True); - - var allMacros = MacroService.GetAll().ToList(); - foreach (var macro in macros) - { - Assert.That(allMacros.Any(x => x.Alias == macro.Alias), Is.True); - } - } - - [Test] - public void Can_Import_Macros_With_Properties() - { - // Arrange - var strXml = ImportResources.XsltSearch_Package; - var xml = XElement.Parse(strXml); - var macrosElement = xml.Descendants("Macros").First(); - - // Act - var macros = PackageDataInstallation.ImportMacros( - macrosElement.Elements("macro"), - -1).ToList(); - - // Assert - Assert.That(macros.Any(), Is.True); - Assert.That(macros.First().Properties.Values.Any(), Is.True); - - var allMacros = MacroService.GetAll().ToList(); - foreach (var macro in macros) - { - Assert.That(allMacros.Any(x => x.Alias == macro.Alias), Is.True); - } - } - [Test] [LongRunning] public void Can_Import_Package_With_Compositions() diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Packaging/PackageInstallationTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Packaging/PackageInstallationTest.cs index 5f612c8c27..81fb0b28e3 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Packaging/PackageInstallationTest.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Packaging/PackageInstallationTest.cs @@ -78,7 +78,6 @@ public class PackageInstallationTest : UmbracoIntegrationTest Assert.AreEqual("3593d8e7-8b35-47b9-beda-5e830ca8c93c", dataType.LastAttribute?.Value); Assert.AreEqual("Document Type Picker", dataType.FirstAttribute?.Value); Assert.IsNotNull(preInstallWarnings); - Assert.AreEqual(0, preInstallWarnings.ConflictingMacros.Count()); Assert.AreEqual(0, preInstallWarnings.ConflictingStylesheets.Count()); Assert.AreEqual(0, preInstallWarnings.ConflictingTemplates.Count()); }); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs deleted file mode 100644 index d3ce181cdc..0000000000 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/MacroRepositoryTest.cs +++ /dev/null @@ -1,431 +0,0 @@ -// Copyright (c) Umbraco. -// See LICENSE for more details. - -using System.Data.Common; -using System.Linq; -using Microsoft.Extensions.Logging; -using NUnit.Framework; -using Umbraco.Cms.Core.Cache; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement; -using Umbraco.Cms.Infrastructure.Scoping; -using Umbraco.Cms.Tests.Common.Testing; -using Umbraco.Cms.Tests.Integration.Testing; - -namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositories; - -[TestFixture] -[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] -public class MacroRepositoryTest : UmbracoIntegrationTest -{ - [SetUp] - public void SetUp() - { - _logger = LoggerFactory.CreateLogger(); - CreateTestData(); - } - - private ILogger _logger; - - [Test] - public void Cannot_Add_Duplicate_Macros() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - var macro = new Macro(ShortStringHelper, "test1", "Test", "~/views/macropartials/test.cshtml"); - - Assert.That(() => repository.Save(macro), Throws.InstanceOf()); - } - } - - [Test] - public void Cannot_Update_To_Duplicate_Macro_Alias() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - var macro = repository.Get(1); - macro.Alias = "test2"; - - Assert.That(() => repository.Save(macro), Throws.InstanceOf()); - } - } - - [Test] - public void Can_Instantiate_Repository() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - // Assert - Assert.That(repository, Is.Not.Null); - } - } - - [Test] - public void Can_Perform_Get_On_Repository() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - // Act - var macro = repository.Get(1); - - // Assert - Assert.That(macro, Is.Not.Null); - Assert.That(macro.HasIdentity, Is.True); - Assert.That(macro.Alias, Is.EqualTo("test1")); - Assert.That(macro.CacheByPage, Is.EqualTo(false)); - Assert.That(macro.CacheByMember, Is.EqualTo(false)); - Assert.That(macro.DontRender, Is.EqualTo(true)); - Assert.That(macro.Name, Is.EqualTo("Test1")); - Assert.That(macro.CacheDuration, Is.EqualTo(0)); - Assert.That(macro.MacroSource, Is.EqualTo("~/views/macropartials/test1.cshtml")); - Assert.That(macro.UseInEditor, Is.EqualTo(false)); - } - } - - [Test] - public void Can_Perform_GetAll_On_Repository() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - // Act - var macros = repository.GetMany(); - - // Assert - Assert.That(macros.Count(), Is.EqualTo(3)); - } - } - - [Test] - public void Can_Perform_GetByQuery_On_Repository() - { - // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - // Act - var query = ScopeAccessor.AmbientScope.SqlContext.Query().Where(x => x.Alias.ToUpper() == "TEST1"); - var result = repository.Get(query); - - // Assert - Assert.AreEqual(1, result.Count()); - } - } - - [Test] - public void Can_Perform_Count_On_Repository() - { - // Arrange - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - // Act - var query = ScopeAccessor.AmbientScope.SqlContext.Query().Where(x => x.Name.StartsWith("Test")); - var count = repository.Count(query); - - // Assert - Assert.That(count, Is.EqualTo(2)); - } - } - - [Test] - public void Can_Perform_Add_On_Repository() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - // Act - var macro = new Macro(ShortStringHelper, "test", "Test", "~/views/macropartials/test.cshtml"); - macro.Properties.Add(new MacroProperty("test", "Test", 0, "test")); - repository.Save(macro); - - // Assert - Assert.That(macro.HasIdentity, Is.True); - Assert.That(macro.Id, Is.EqualTo(4)); // With 3 existing entries the Id should be 4 - Assert.Greater(macro.Properties.Values.Single().Id, 0); - } - } - - [Test] - public void Can_Perform_Update_On_Repository() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - // Act - var macro = repository.Get(2); - macro.Name = "Hello"; - macro.CacheDuration = 1234; - macro.CacheByPage = true; - macro.CacheByMember = true; - macro.DontRender = false; - macro.MacroSource = "~/newpath.cshtml"; - macro.UseInEditor = true; - - repository.Save(macro); - - var macroUpdated = repository.Get(2); - - // Assert - Assert.That(macroUpdated, Is.Not.Null); - Assert.That(macroUpdated.Name, Is.EqualTo("Hello")); - Assert.That(macroUpdated.CacheDuration, Is.EqualTo(1234)); - Assert.That(macroUpdated.CacheByPage, Is.EqualTo(true)); - Assert.That(macroUpdated.CacheByMember, Is.EqualTo(true)); - Assert.That(macroUpdated.DontRender, Is.EqualTo(false)); - Assert.That(macroUpdated.MacroSource, Is.EqualTo("~/newpath.cshtml")); - Assert.That(macroUpdated.UseInEditor, Is.EqualTo(true)); - } - } - - [Test] - public void Can_Perform_Delete_On_Repository() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - // Act - var macro = repository.Get(3); - Assert.IsNotNull(macro); - repository.Delete(macro); - - var exists = repository.Exists(3); - - // Assert - Assert.That(exists, Is.False); - } - } - - [Test] - public void Can_Perform_Exists_On_Repository() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - // Act - var exists = repository.Exists(3); - var doesntExist = repository.Exists(10); - - // Assert - Assert.That(exists, Is.True); - Assert.That(doesntExist, Is.False); - } - } - - [Test] - public void Can_Add_Property_For_Macro() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - var macro = repository.Get(1); - macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); - - repository.Save(macro); - - // Assert - Assert.Greater(macro.Properties.Values.First().Id, 0); // ensure id is returned - var result = repository.Get(1); - Assert.Greater(result.Properties.Values.First().Id, 0); - Assert.AreEqual(1, result.Properties.Values.Count()); - Assert.AreEqual("new1", result.Properties.Values.First().Alias); - Assert.AreEqual("New1", result.Properties.Values.First().Name); - Assert.AreEqual(3, result.Properties.Values.First().SortOrder); - } - } - - [Test] - public void Can_Add_New_Macro_With_Property() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - var macro = new Macro(ShortStringHelper, "newmacro", "A new macro", "~/views/macropartials/test1.cshtml"); - macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); - - repository.Save(macro); - - // Assert - var result = repository.Get(macro.Id); - Assert.AreEqual(1, result.Properties.Values.Count()); - Assert.AreEqual("blah1", result.Properties.Values.First().Alias); - Assert.AreEqual("New1", result.Properties.Values.First().Name); - Assert.AreEqual(4, result.Properties.Values.First().SortOrder); - } - } - - [Test] - public void Can_Remove_Macro_Property() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - var macro = new Macro(ShortStringHelper, "newmacro", "A new macro", "~/views/macropartials/test1.cshtml"); - macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); - repository.Save(macro); - - var result = repository.Get(macro.Id); - result.Properties.Remove("blah1"); - repository.Save(result); - - // Assert - result = repository.Get(macro.Id); - Assert.AreEqual(0, result.Properties.Values.Count()); - } - } - - [Test] - public void Can_Add_Remove_Macro_Properties() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - var macro = new Macro(ShortStringHelper, "newmacro", "A new macro", "~/views/macropartials/test1.cshtml"); - var prop1 = new MacroProperty("blah1", "New1", 4, "test.editor"); - var prop2 = new MacroProperty("blah2", "New2", 3, "test.editor"); - - // add/remove a few to test the collection observable - macro.Properties.Add(prop1); - macro.Properties.Add(prop2); - macro.Properties.Remove(prop1); - macro.Properties.Remove("blah2"); - macro.Properties.Add(prop2); - - repository.Save(macro); - - // Assert - var result = repository.Get(macro.Id); - - Assert.AreEqual(1, result.Properties.Values.Count()); - Assert.AreEqual("blah2", result.Properties.Values.Single().Alias); - } - } - - [Test] - public void Can_Update_Property_For_Macro() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - var macro = repository.Get(1); - macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); - repository.Save(macro); - - // Act - macro = repository.Get(1); - macro.Properties["new1"].Name = "this is a new name"; - repository.Save(macro); - - // Assert - var result = repository.Get(1); - Assert.AreEqual("new1", result.Properties.Values.First().Alias); - Assert.AreEqual("this is a new name", result.Properties.Values.First().Name); - } - } - - [Test] - public void Can_Update_Macro_Property_Alias() - { - // Arrange - var provider = ScopeProvider; - using (provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - var macro = repository.Get(1); - macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); - repository.Save(macro); - - // Act - macro = repository.Get(1); - macro.Properties.UpdateProperty("new1", newAlias: "newAlias"); - repository.Save(macro); - - // Assert - var result = repository.Get(1); - Assert.AreEqual("newAlias", result.Properties.Values.First().Alias); - } - } - - public void CreateTestData() - { - var provider = ScopeProvider; - using (var scope = provider.CreateScope()) - { - var repository = - new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); - - repository.Save(new Macro(ShortStringHelper, "test1", "Test1", "~/views/macropartials/test1.cshtml")); - repository.Save(new Macro(ShortStringHelper, "test2", "Test2", "~/views/macropartials/test2.cshtml")); - repository.Save(new Macro(ShortStringHelper, "test3", "Tet3", "~/views/macropartials/test3.cshtml")); - scope.Complete(); - } - } -} diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs index 5f70ae04bf..60b1833360 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/PartialViewRepositoryTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Umbraco. // See LICENSE for more details. -using System.IO; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NUnit.Framework; @@ -51,7 +50,6 @@ public class PartialViewRepositoryTests : UmbracoIntegrationTest IOHelper, GetRequiredService>(), HostingEnvironment, - null, _fileSystem, null, null, @@ -63,14 +61,14 @@ public class PartialViewRepositoryTests : UmbracoIntegrationTest var repository = new PartialViewRepository(fileSystems); IPartialView partialView = - new PartialView(PartialViewType.PartialView, "test-path-1.cshtml") { Content = "// partialView" }; + new PartialView("test-path-1.cshtml") { Content = "// partialView" }; repository.Save(partialView); Assert.IsTrue(_fileSystem.FileExists("test-path-1.cshtml")); Assert.AreEqual("test-path-1.cshtml", partialView.Path); Assert.AreEqual("/Views/Partials/test-path-1.cshtml", partialView.VirtualPath); partialView = - new PartialView(PartialViewType.PartialView, "path-2/test-path-2.cshtml") { Content = "// partialView" }; + new PartialView("path-2/test-path-2.cshtml") { Content = "// partialView" }; repository.Save(partialView); Assert.IsTrue(_fileSystem.FileExists("path-2/test-path-2.cshtml")); Assert.AreEqual("path-2\\test-path-2.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); @@ -82,7 +80,7 @@ public class PartialViewRepositoryTests : UmbracoIntegrationTest Assert.AreEqual("/Views/Partials/path-2/test-path-2.cshtml", partialView.VirtualPath); partialView = - new PartialView(PartialViewType.PartialView, "path-2\\test-path-3.cshtml") { Content = "// partialView" }; + new PartialView("path-2\\test-path-3.cshtml") { Content = "// partialView" }; repository.Save(partialView); Assert.IsTrue(_fileSystem.FileExists("path-2/test-path-3.cshtml")); Assert.AreEqual("path-2\\test-path-3.cshtml".Replace("\\", $"{Path.DirectorySeparatorChar}"), partialView.Path); @@ -99,12 +97,12 @@ public class PartialViewRepositoryTests : UmbracoIntegrationTest Assert.AreEqual("/Views/Partials/path-2/test-path-3.cshtml", partialView.VirtualPath); partialView = - new PartialView(PartialViewType.PartialView, "..\\test-path-4.cshtml") { Content = "// partialView" }; + new PartialView("..\\test-path-4.cshtml") { Content = "// partialView" }; Assert.Throws(() => repository.Save(partialView)); partialView = - new PartialView(PartialViewType.PartialView, "\\test-path-5.cshtml") { Content = "// partialView" }; + new PartialView("\\test-path-5.cshtml") { Content = "// partialView" }; repository.Save(partialView); partialView = repository.Get("\\test-path-5.cshtml"); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs index 5d5498981a..4c9cd11394 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/ScriptRepositoryTest.cs @@ -36,7 +36,6 @@ public class ScriptRepositoryTest : UmbracoIntegrationTest HostingEnvironment, null, null, - null, _fileSystem, null); using (var stream = CreateStream("Umbraco.Sys.registerNamespace(\"Umbraco.Utils\");")) diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs index 97f0cc7fd1..e5baca9776 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/Repositories/StylesheetRepositoryTest.cs @@ -36,7 +36,6 @@ public class StylesheetRepositoryTest : UmbracoIntegrationTest GetRequiredService>(), HostingEnvironment, null, - null, _fileSystem, null, null); diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs index d6a0fd2a5a..b370241965 100644 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs +++ b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/EntityXmlSerializerTests.cs @@ -42,27 +42,6 @@ public class EntityXmlSerializerTests : UmbracoIntegrationTest private ILocalizedTextService TextService => GetRequiredService(); private IFileService FileService => GetRequiredService(); - [Test] - public void Can_Export_Macro() - { - // Arrange - var macroService = GetRequiredService(); - var macro = new MacroBuilder() - .WithAlias("test1") - .WithName("Test") - .Build(); - macroService.Save(macro); - - // Act - var element = Serializer.Serialize(macro); - - // Assert - Assert.That(element, Is.Not.Null); - Assert.That(element.Element("name").Value, Is.EqualTo("Test")); - Assert.That(element.Element("alias").Value, Is.EqualTo("test1")); - Debug.Print(element.ToString()); - } - [Test] public async Task Can_Export_DictionaryItems() { diff --git a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.cs b/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.cs deleted file mode 100644 index d3ae791f52..0000000000 --- a/tests/Umbraco.Tests.Integration/Umbraco.Infrastructure/Services/MacroServiceTests.cs +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright (c) Umbraco. -// See LICENSE for more details. - -using System.Linq; -using Microsoft.Extensions.Logging; -using Moq; -using NUnit.Framework; -using Umbraco.Cms.Core.Cache; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Services; -using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement; -using Umbraco.Cms.Infrastructure.Scoping; -using Umbraco.Cms.Tests.Common.Builders; -using Umbraco.Cms.Tests.Common.Builders.Extensions; -using Umbraco.Cms.Tests.Common.Testing; -using Umbraco.Cms.Tests.Integration.Testing; - -namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Services; - -[TestFixture] -[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] -public class MacroServiceTests : UmbracoIntegrationTest -{ - - private IMacroService MacroService => GetRequiredService(); - - [SetUp] - public void SetupTest() - { - var scopeProvider = ScopeProvider; - using (var scope = scopeProvider.CreateScope()) - { - var repository = new MacroRepository((IScopeAccessor)scopeProvider, AppCaches.Disabled, - Mock.Of>(), ShortStringHelper); - - repository.Save(new Macro(ShortStringHelper, "test1", "Test1", "~/views/macropartials/test1.cshtml")); - repository.Save(new Macro(ShortStringHelper, "test2", "Test2", "~/views/macropartials/test2.cshtml")); - repository.Save(new Macro(ShortStringHelper, "test3", "Tet3", "~/views/macropartials/test3.cshtml")); - scope.Complete(); - } - } - - [Test] - public void Can_Get_By_Alias() - { - // Act - var macro = MacroService.GetByAlias("test1"); - - // Assert - Assert.IsNotNull(macro); - Assert.AreEqual("Test1", macro.Name); - } - - [Test] - public void Can_Get_By_Aliases() - { - // Act - var macros = MacroService.GetAll("test1", "test2"); - - // Assert - Assert.IsNotNull(macros); - Assert.AreEqual(2, macros.Count()); - Assert.AreEqual("Test1", macros.ToArray()[0].Name); - Assert.AreEqual("Test2", macros.ToArray()[1].Name); - } - - [Test] - public void Can_Get_All() - { - // Act - var result = MacroService.GetAll(); - - // Assert - Assert.AreEqual(3, result.Count()); - } - - [Test] - public void Can_Create() - { - // Act - var macro = CreateMacro(); - MacroService.Save(macro); - - // Assert - Assert.IsTrue(macro.HasIdentity); - Assert.Greater(macro.Id, 0); - Assert.AreNotEqual(Guid.Empty, macro.Key); - var result = MacroService.GetById(macro.Id); - Assert.AreEqual("test", result.Alias); - Assert.AreEqual("Test", result.Name); - Assert.AreEqual("~/Views/MacroPartials/Test.cshtml", result.MacroSource); - Assert.AreEqual(1234, result.CacheDuration); - - result = MacroService.GetById(macro.Key); - Assert.AreEqual("test", result.Alias); - Assert.AreEqual("Test", result.Name); - Assert.AreEqual("~/Views/MacroPartials/Test.cshtml", result.MacroSource); - Assert.AreEqual(1234, result.CacheDuration); - } - - [Test] - public void Can_Delete() - { - // Arrange - var macro = new Macro(ShortStringHelper, "test", "Test", "~/Views/MacroPartials/Test.cshtml", - cacheDuration: 1234); - MacroService.Save(macro); - - // Act - MacroService.Delete(macro); - - // Assert - var result = MacroService.GetById(macro.Id); - Assert.IsNull(result); - - result = MacroService.GetById(macro.Key); - Assert.IsNull(result); - } - - [Test] - public void Can_Update() - { - // Arrange - var macro = CreateMacro(); - MacroService.Save(macro); - - // Act - var currKey = macro.Key; - macro.Name = "New name"; - macro.Alias = "NewAlias"; - MacroService.Save(macro); - - macro = MacroService.GetById(macro.Id); - - // Assert - Assert.AreEqual("New name", macro.Name); - Assert.AreEqual("NewAlias", macro.Alias); - Assert.AreEqual(currKey, macro.Key); - } - - [Test] - public void Can_Update_Property() - { - // Arrange - var macro = CreateMacro(); - macro.Properties.Add(new MacroProperty("blah", "Blah", 0, "blah")); - MacroService.Save(macro); - - Assert.AreNotEqual(Guid.Empty, macro.Properties[0].Key); - - // Act - var currPropKey = macro.Properties[0].Key; - macro.Properties[0].Alias = "new Alias"; - macro.Properties[0].Name = "new Name"; - macro.Properties[0].SortOrder = 1; - macro.Properties[0].EditorAlias = "new"; - MacroService.Save(macro); - - macro = MacroService.GetById(macro.Id); - - // Assert - Assert.AreEqual(1, macro.Properties.Count); - Assert.AreEqual(currPropKey, macro.Properties[0].Key); - Assert.AreEqual("new Alias", macro.Properties[0].Alias); - Assert.AreEqual("new Name", macro.Properties[0].Name); - Assert.AreEqual(1, macro.Properties[0].SortOrder); - Assert.AreEqual("new", macro.Properties[0].EditorAlias); - Assert.AreEqual(currPropKey, macro.Properties[0].Key); - } - - [Test] - public void Can_Update_Remove_Property() - { - // Arrange - var macro = CreateMacro(); - macro.Properties.Add(new MacroProperty("blah1", "Blah1", 0, "blah1")); - macro.Properties.Add(new MacroProperty("blah2", "Blah2", 1, "blah2")); - macro.Properties.Add(new MacroProperty("blah3", "Blah3", 2, "blah3")); - MacroService.Save(macro); - - var lastKey = macro.Properties[0].Key; - for (var i = 1; i < macro.Properties.Count; i++) - { - Assert.AreNotEqual(Guid.Empty, macro.Properties[i].Key); - Assert.AreNotEqual(lastKey, macro.Properties[i].Key); - lastKey = macro.Properties[i].Key; - } - - // Act - macro.Properties["blah1"].Alias = "newAlias"; - macro.Properties["blah1"].Name = "new Name"; - macro.Properties["blah1"].SortOrder = 1; - macro.Properties["blah1"].EditorAlias = "new"; - macro.Properties.Remove("blah3"); - - var allPropKeys = macro.Properties.Values.Select(x => new { x.Alias, x.Key }).ToArray(); - - MacroService.Save(macro); - - macro = MacroService.GetById(macro.Id); - - // Assert - Assert.AreEqual(2, macro.Properties.Count); - Assert.AreEqual("newAlias", macro.Properties["newAlias"].Alias); - Assert.AreEqual("new Name", macro.Properties["newAlias"].Name); - Assert.AreEqual(1, macro.Properties["newAlias"].SortOrder); - Assert.AreEqual("new", macro.Properties["newAlias"].EditorAlias); - foreach (var propKey in allPropKeys) - { - Assert.AreEqual(propKey.Key, macro.Properties[propKey.Alias].Key); - } - } - - [Test] - public void Can_Add_And_Remove_Properties() - { - var macro = CreateMacro(); - - // Adds some properties - macro.Properties.Add(new MacroProperty("blah1", "Blah1", 0, "blah1")); - macro.Properties.Add(new MacroProperty("blah2", "Blah2", 0, "blah2")); - macro.Properties.Add(new MacroProperty("blah3", "Blah3", 0, "blah3")); - macro.Properties.Add(new MacroProperty("blah4", "Blah4", 0, "blah4")); - MacroService.Save(macro); - - var result1 = MacroService.GetById(macro.Id); - Assert.AreEqual(4, result1.Properties.Values.Count()); - - // Simulate clearing the sections - foreach (var s in result1.Properties.Values.ToArray()) - { - result1.Properties.Remove(s.Alias); - } - - // Now just re-add a couple - result1.Properties.Add(new MacroProperty("blah3", "Blah3", 0, "blah3")); - result1.Properties.Add(new MacroProperty("blah4", "Blah4", 0, "blah4")); - MacroService.Save(result1); - - // Assert - result1 = MacroService.GetById(result1.Id); - Assert.AreEqual(2, result1.Properties.Values.Count()); - } - - [Test] - public void Cannot_Save_Macro_With_Empty_Name() - { - // Arrange - var macro = CreateMacro(string.Empty); - - // Act & Assert - Assert.Throws(() => MacroService.Save(macro)); - } - - private static IMacro CreateMacro(string name = "Test") => - new MacroBuilder() - .WithAlias("test") - .WithName(name) - .WithSource("~/Views/MacroPartials/Test.cshtml") - .WithCacheDuration(1234) - .Build(); -} diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/AppCacheTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/AppCacheTests.cs index a207a257fe..588a669de6 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/AppCacheTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Cache/AppCacheTests.cs @@ -125,9 +125,9 @@ public abstract class AppCacheTests [Test] public void Can_Get_By_Search() { - var cacheContent1 = new MacroCacheContent(); - var cacheContent2 = new MacroCacheContent(); - var cacheContent3 = new MacroCacheContent(); + var cacheContent1 = new CacheContent(); + var cacheContent2 = new CacheContent(); + var cacheContent3 = new CacheContent(); var cacheContent4 = new LiteralControl(); AppCache.Get("Test1", () => cacheContent1); AppCache.Get("Tester2", () => cacheContent2); @@ -144,9 +144,9 @@ public abstract class AppCacheTests [Test] public void Can_Clear_By_Expression() { - var cacheContent1 = new MacroCacheContent(); - var cacheContent2 = new MacroCacheContent(); - var cacheContent3 = new MacroCacheContent(); + var cacheContent1 = new CacheContent(); + var cacheContent2 = new CacheContent(); + var cacheContent3 = new CacheContent(); var cacheContent4 = new LiteralControl(); AppCache.Get("TTes1t", () => cacheContent1); AppCache.Get("Tester2", () => cacheContent2); @@ -163,9 +163,9 @@ public abstract class AppCacheTests [Test] public void Can_Clear_By_Search() { - var cacheContent1 = new MacroCacheContent(); - var cacheContent2 = new MacroCacheContent(); - var cacheContent3 = new MacroCacheContent(); + var cacheContent1 = new CacheContent(); + var cacheContent2 = new CacheContent(); + var cacheContent3 = new CacheContent(); var cacheContent4 = new LiteralControl(); AppCache.Get("Test1", () => cacheContent1); AppCache.Get("Tester2", () => cacheContent2); @@ -182,9 +182,9 @@ public abstract class AppCacheTests [Test] public void Can_Clear_By_Key() { - var cacheContent1 = new MacroCacheContent(); - var cacheContent2 = new MacroCacheContent(); - var cacheContent3 = new MacroCacheContent(); + var cacheContent1 = new CacheContent(); + var cacheContent2 = new CacheContent(); + var cacheContent3 = new CacheContent(); var cacheContent4 = new LiteralControl(); AppCache.Get("Test1", () => cacheContent1); AppCache.Get("Test2", () => cacheContent2); @@ -202,9 +202,9 @@ public abstract class AppCacheTests [Test] public void Can_Clear_All_Items() { - var cacheContent1 = new MacroCacheContent(); - var cacheContent2 = new MacroCacheContent(); - var cacheContent3 = new MacroCacheContent(); + var cacheContent1 = new CacheContent(); + var cacheContent2 = new CacheContent(); + var cacheContent3 = new CacheContent(); var cacheContent4 = new LiteralControl(); AppCache.Get("Test1", () => cacheContent1); AppCache.Get("Test2", () => cacheContent2); @@ -221,7 +221,7 @@ public abstract class AppCacheTests [Test] public void Can_Add_When_Not_Available() { - var cacheContent1 = new MacroCacheContent(); + var cacheContent1 = new CacheContent(); AppCache.Get("Test1", () => cacheContent1); Assert.AreEqual(1, GetTotalItemCount); } @@ -229,7 +229,7 @@ public abstract class AppCacheTests [Test] public void Can_Get_When_Available() { - var cacheContent1 = new MacroCacheContent(); + var cacheContent1 = new CacheContent(); var result = AppCache.Get("Test1", () => cacheContent1); var result2 = AppCache.Get("Test1", () => cacheContent1); Assert.AreEqual(1, GetTotalItemCount); @@ -239,9 +239,9 @@ public abstract class AppCacheTests [Test] public void Can_Remove_By_Type_Name() { - var cacheContent1 = new MacroCacheContent(); - var cacheContent2 = new MacroCacheContent(); - var cacheContent3 = new MacroCacheContent(); + var cacheContent1 = new CacheContent(); + var cacheContent2 = new CacheContent(); + var cacheContent3 = new CacheContent(); var cacheContent4 = new LiteralControl(); AppCache.Get("Test1", () => cacheContent1); AppCache.Get("Test2", () => cacheContent2); @@ -250,8 +250,7 @@ public abstract class AppCacheTests Assert.AreEqual(4, GetTotalItemCount); - ////Provider.ClearCacheObjectTypes("umbraco.MacroCacheContent"); - AppCache.ClearOfType(); + AppCache.ClearOfType(); Assert.AreEqual(1, GetTotalItemCount); } @@ -259,9 +258,9 @@ public abstract class AppCacheTests [Test] public void Can_Remove_By_Strong_Type() { - var cacheContent1 = new MacroCacheContent(); - var cacheContent2 = new MacroCacheContent(); - var cacheContent3 = new MacroCacheContent(); + var cacheContent1 = new CacheContent(); + var cacheContent2 = new CacheContent(); + var cacheContent3 = new CacheContent(); var cacheContent4 = new LiteralControl(); AppCache.Get("Test1", () => cacheContent1); AppCache.Get("Test2", () => cacheContent2); @@ -270,13 +269,13 @@ public abstract class AppCacheTests Assert.AreEqual(4, GetTotalItemCount); - AppCache.ClearOfType(); + AppCache.ClearOfType(); Assert.AreEqual(1, GetTotalItemCount); } // Just used for these tests - private class MacroCacheContent + private class CacheContent { } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderTests.cs index 69f90158ff..d02da0dda9 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Composing/TypeLoaderTests.cs @@ -79,41 +79,6 @@ public class TypeLoaderTests return dir; } - ////[Test] - ////public void Scan_Vs_Load_Benchmark() - ////{ - //// var typeLoader = new TypeLoader(false); - //// var watch = new Stopwatch(); - //// watch.Start(); - //// for (var i = 0; i < 1000; i++) - //// { - //// var type2 = Type.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); - //// var type3 = Type.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); - //// var type4 = Type.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); - //// var type5 = Type.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); - //// } - //// watch.Stop(); - //// Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds); - //// watch.Start(); - //// for (var i = 0; i < 1000; i++) - //// { - //// var type2 = BuildManager.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); - //// var type3 = BuildManager.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); - //// var type4 = BuildManager.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); - //// var type5 = BuildManager.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); - //// } - //// watch.Stop(); - //// Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds); - //// watch.Reset(); - //// watch.Start(); - //// for (var i = 0; i < 1000; i++) - //// { - //// var refreshers = typeLoader.GetTypes(false); - //// } - //// watch.Stop(); - //// Debug.WriteLine("TOTAL TIME (2nd round): " + watch.ElapsedMilliseconds); - ////} - [Test] public void Get_Plugins_Hash_With_Hash_Generator() { diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/UdiTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/UdiTests.cs index c5f2b4d1bf..b7adfe85d7 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/UdiTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/CoreThings/UdiTests.cs @@ -82,12 +82,12 @@ public class UdiTests // we want to keep the / in string udis var r = string.Join("/", "path/to/View[1].cshtml".Split('/').Select(Uri.EscapeDataString)); Assert.AreEqual("path/to/View%5B1%5D.cshtml", r); - Assert.IsTrue(Uri.IsWellFormedUriString("umb://partial-view-macro/" + r, UriKind.Absolute)); + Assert.IsTrue(Uri.IsWellFormedUriString("umb://partial-view/" + r, UriKind.Absolute)); // with the proper fix in StringUdi this should work: - var udi1 = new StringUdi("partial-view-macro", "path/to/View[1].cshtml"); - Assert.AreEqual("umb://partial-view-macro/path/to/View%5B1%5D.cshtml", udi1.ToString()); - var udi2 = UdiParser.Parse("umb://partial-view-macro/path/to/View%5B1%5D.cshtml"); + var udi1 = new StringUdi("partial-view", "path/to/View[1].cshtml"); + Assert.AreEqual("umb://partial-view/path/to/View%5B1%5D.cshtml", udi1.ToString()); + var udi2 = UdiParser.Parse("umb://partial-view/path/to/View%5B1%5D.cshtml"); Assert.AreEqual("path/to/View[1].cshtml", ((StringUdi)udi2).Id); } diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/NavigableNavigatorTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/NavigableNavigatorTests.cs index ab838d358f..d03ae8d58c 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/NavigableNavigatorTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/CoreXml/NavigableNavigatorTests.cs @@ -682,135 +682,6 @@ public class NavigableNavigatorTests //// Assert.AreEqual(3, (nav.UnderlyingObject as TestContent).Id); } - [TestCase(true, true)] - [TestCase(true, false)] - [TestCase(false, true)] - [TestCase(false, false)] - public void XsltDebugModeAndSortOrder(bool native, bool debug) - { - const string xml = @" - - - title-1 - - title-3 - - title-7 - - - title-8 - - - - title-5 - - - - title-2 - - title-4 - - - title-6 - - - -"; - - const string xslt = @" - -]> - - - - - - - - - -! - - -!! - - -!!! - - - - - - - -"; - const string expected = @"! title-1 -!! title-3 -!!! title-7 -!!! title-8 -!! title-5 -! title-2 -!! title-4 -!! title-6 -"; - - // see http://www.onenaught.com/posts/352/xslt-performance-tip-dont-indent-output - // why aren't we using an XmlWriter here? - var transform = new XslCompiledTransform(debug); - var xmlReader = new XmlTextReader(new StringReader(xslt)) { EntityHandling = EntityHandling.ExpandEntities }; - var xslResolver = new XmlUrlResolver { Credentials = CredentialCache.DefaultCredentials }; - var args = new XsltArgumentList(); - - // .Default is more restrictive than .TrustedXslt - transform.Load(xmlReader, XsltSettings.Default, xslResolver); - - XPathNavigator macro; - if (!native) - { - var source = new TestSource7(); - ////var nav = new NavigableNavigator(source); - ////args.AddParam("currentPage", string.Empty, nav.Clone()); - - var x = new XmlDocument(); - x.LoadXml(xml); - - macro = new MacroNavigator(new[] - { - // it even fails like that => macro nav. issue? - new MacroNavigator.MacroParameter("nav", x.CreateNavigator()), // nav.Clone()) - }); - } - else - { - var doc = new XmlDocument(); - doc.LoadXml(""); - var nav = doc.CreateElement("nav"); - doc.DocumentElement.AppendChild(nav); - var x = new XmlDocument(); - x.LoadXml(xml); - nav.AppendChild(doc.ImportNode(x.DocumentElement, true)); - macro = doc.CreateNavigator(); - } - - var writer = new StringWriter(); - transform.Transform(macro, args, writer); - - // this was working with native, debug and non-debug - // this was working with macro nav, non-debug - // but was NOT working (changing the order of nodes) with macro nav, debug - // was due to an issue with macro nav IsSamePosition, fixed - - ////Debug.Print("--------"); - ////Debug.Print(writer.ToString()); - Assert.AreEqual(expected.Lf(), writer.ToString().Lf()); - } - [Test] public void WhiteSpacesAndEmptyValues() { diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UdiGetterExtensionsTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UdiGetterExtensionsTests.cs index 1fc5501073..b5da0a4f2f 100644 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UdiGetterExtensionsTests.cs +++ b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UdiGetterExtensionsTests.cs @@ -3,7 +3,6 @@ using NUnit.Framework; using Umbraco.Cms.Core; -using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Entities; using Umbraco.Cms.Tests.Common.Builders; using Umbraco.Cms.Tests.Common.Builders.Extensions; @@ -36,18 +35,14 @@ public class UdiGetterExtensionsTests Assert.AreEqual(expected, result.ToString()); } - [TestCase("test.cshtml", PartialViewType.PartialView, "umb://partial-view/test.cshtml")] - [TestCase("editor\\test.cshtml", PartialViewType.PartialView, "umb://partial-view/editor/test.cshtml")] - [TestCase("editor/test.cshtml", PartialViewType.PartialView, "umb://partial-view/editor/test.cshtml")] - [TestCase("test.cshtml", PartialViewType.PartialViewMacro, "umb://partial-view-macro/test.cshtml")] - [TestCase("editor\\test.cshtml", PartialViewType.PartialViewMacro, "umb://partial-view-macro/editor/test.cshtml")] - [TestCase("editor/test.cshtml", PartialViewType.PartialViewMacro, "umb://partial-view-macro/editor/test.cshtml")] - public void GetUdiForPartialView(string path, PartialViewType viewType, string expected) + [TestCase("test.cshtml", "umb://partial-view/test.cshtml")] + [TestCase("editor\\test.cshtml", "umb://partial-view/editor/test.cshtml")] + [TestCase("editor/test.cshtml", "umb://partial-view/editor/test.cshtml")] + public void GetUdiForPartialView(string path, string expected) { var builder = new PartialViewBuilder(); var partialView = builder .WithPath(path) - .WithViewType(viewType) .Build(); var result = partialView.GetUdi(); Assert.AreEqual(expected, result.ToString()); diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MacroTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MacroTests.cs deleted file mode 100644 index 2e64f03337..0000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Core/Models/MacroTests.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Umbraco. -// See LICENSE for more details. - -using System.Linq; -using NUnit.Framework; -using Umbraco.Cms.Core.Models; -using Umbraco.Cms.Core.Models.Entities; -using Umbraco.Cms.Tests.Common.Builders; -using Umbraco.Cms.Tests.Common.Builders.Extensions; - -namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Models; - -[TestFixture] -public class MacroTests -{ - [SetUp] - public void SetUp() => _builder = new MacroBuilder(); - - private MacroBuilder _builder; - - [Test] - public void Can_Deep_Clone() - { - var macro = _builder - .WithId(1) - .WithUseInEditor(true) - .WithCacheDuration(3) - .WithAlias("test") - .WithName("Test") - .WithSource("~/script.cshtml") - .WithCacheByMember(true) - .WithDontRender(true) - .AddProperty() - .WithId(6) - .WithAlias("rewq") - .WithName("REWQ") - .WithSortOrder(1) - .WithEditorAlias("asdfasdf") - .Done() - .Build(); - - var clone = (Macro)macro.DeepClone(); - - Assert.AreNotSame(clone, macro); - Assert.AreEqual(clone, macro); - Assert.AreEqual(clone.Id, macro.Id); - - Assert.AreEqual(clone.Properties.Count, macro.Properties.Count); - - for (var i = 0; i < clone.Properties.Count; i++) - { - Assert.AreEqual(clone.Properties[i], macro.Properties[i]); - Assert.AreNotSame(clone.Properties[i], macro.Properties[i]); - } - - Assert.AreNotSame(clone.Properties, macro.Properties); - Assert.AreNotSame(clone.AddedProperties, macro.AddedProperties); - Assert.AreNotSame(clone.RemovedProperties, macro.RemovedProperties); - - // This double verifies by reflection - var allProps = clone.GetType().GetProperties(); - foreach (var propertyInfo in allProps) - { - Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(macro, null)); - } - - // Need to ensure the event handlers are wired. - var asDirty = (ICanBeDirty)clone; - - Assert.IsFalse(asDirty.IsPropertyDirty("Properties")); - clone.Properties.Add(new MacroProperty(3, Guid.NewGuid(), "asdf", "SDF", 3, "asdfasdf")); - Assert.IsTrue(asDirty.IsPropertyDirty("Properties")); - Assert.AreEqual(1, clone.AddedProperties.Count()); - clone.Properties.Remove("rewq"); - Assert.AreEqual(1, clone.RemovedProperties.Count()); - } -} diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MacroBuilderTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MacroBuilderTests.cs deleted file mode 100644 index 57aac4541f..0000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/MacroBuilderTests.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Umbraco. -// See LICENSE for more details. - -using NUnit.Framework; -using Umbraco.Cms.Tests.Common.Builders; -using Umbraco.Cms.Tests.Common.Builders.Extensions; - -namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Tests.Common.Builders; - -[TestFixture] -public class MacroBuilderTests -{ - [Test] - public void Is_Built_Correctly() - { - // Arrange - const int id = 1; - var key = Guid.NewGuid(); - const bool useInEditor = true; - const int cacheDuration = 3; - const string alias = "test"; - const string name = "Test"; - const string source = "~/script.cshtml"; - const bool cacheByPage = false; - const bool cacheByMember = true; - const bool dontRender = true; - const int propertyId = 6; - const string propertyAlias = "rewq"; - const string propertyName = "REWQ"; - const int propertySortOrder = 1; - const string propertyEditorAlias = "asdfasdf"; - - var builder = new MacroBuilder(); - - // Act - var macro = builder - .WithId(id) - .WithKey(key) - .WithUseInEditor(useInEditor) - .WithCacheDuration(cacheDuration) - .WithAlias(alias) - .WithName(name) - .WithSource(source) - .WithCacheByPage(cacheByPage) - .WithCacheByMember(cacheByMember) - .WithDontRender(dontRender) - .AddProperty() - .WithId(propertyId) - .WithAlias(propertyAlias) - .WithName(propertyName) - .WithSortOrder(propertySortOrder) - .WithEditorAlias(propertyEditorAlias) - .Done() - .Build(); - - // Assert - Assert.AreEqual(id, macro.Id); - Assert.AreEqual(key, macro.Key); - Assert.AreEqual(useInEditor, macro.UseInEditor); - Assert.AreEqual(cacheDuration, macro.CacheDuration); - Assert.AreEqual(alias, macro.Alias); - Assert.AreEqual(name, macro.Name); - Assert.AreEqual(source, macro.MacroSource); - Assert.AreEqual(cacheByPage, macro.CacheByPage); - Assert.AreEqual(cacheByMember, macro.CacheByMember); - Assert.AreEqual(dontRender, macro.DontRender); - Assert.AreEqual(1, macro.Properties.Count); - Assert.AreEqual(propertyId, macro.Properties[0].Id); - Assert.AreEqual(propertyAlias, macro.Properties[0].Alias); - Assert.AreEqual(propertyName, macro.Properties[0].Name); - Assert.AreEqual(propertySortOrder, macro.Properties[0].SortOrder); - Assert.AreEqual(propertyEditorAlias, macro.Properties[0].EditorAlias); - } -} diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroParserTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroParserTests.cs deleted file mode 100644 index 63300eaa1b..0000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroParserTests.cs +++ /dev/null @@ -1,420 +0,0 @@ -// Copyright (c) Umbraco. -// See LICENSE for more details. - -using System.Collections.Generic; -using NUnit.Framework; -using Umbraco.Cms.Infrastructure.Macros; -using Umbraco.Cms.Tests.Common.Extensions; -using Umbraco.Cms.Tests.Common.TestHelpers; - -namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Web.Common.Macros; - -[TestFixture] -public class MacroParserTests -{ - [Test] - [TestCase(@"

hello world

")] - public void Format_RTE_Data_For_Editor_With_No_Macros(string expected) - { - var content = expected; - var result = MacroTagParser.FormatRichTextContentForPersistence(content); - Assert.AreEqual(expected, result); - } - - [Test] - public void Format_RTE_Data_For_Editor_With_Non_AlphaNumeric_Char_In_Alias() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "test2", "value2" } }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

-
- -Macro alias: My.Map.isCool eh[boy!]
-

asdfasdf

".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Editor() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "test2", "value2" } }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

-
- -Macro alias: Map
-

asdfasdf

".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Editor_Closing_Tag() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "test2", "value2" } }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

-
- -Macro alias: Map
-

asdfasdf

".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Editor_With_Params() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "test2", "value2" } }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

-
- -Macro alias: Map
-

asdfasdf

".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Editor_With_Params_When_MacroAlias_Not_First() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "test2", "value2" } }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

-
- -Macro alias: Map
-

asdfasdf

".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Editor_With_Params_When_MacroAlias_Is_First() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "test2", "value2" } }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

-
- -Macro alias: Map
-

asdfasdf

".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Editor_With_Params_When_Multiple_Macros() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfsadf

- -

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "test2", "value2" } }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

-
- -Macro alias: Map
-

asdfsadf

-
- -Macro alias: Map
-

asdfsadf

-
- -Macro alias: Map
-

asdfasdf

".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Editor_With_Multiple_Macros() - { - var content = @"

asdfasdf

- -

asdfsadf

-

 

- -

 

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary()); - - Assert.AreEqual( - @"

asdfasdf

-
- -Macro alias: Breadcrumb
-

asdfsadf

-

 

-
- -Macro alias: login
-

 

".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Persistence_Multiline_Parameters() - { - var content = @" - -

asdfasdf

-
- -asdfasdf -asdfas -asdfasdfasdf -

asdfasdf

-
-asdfdasf -
-asdfsdf -
- -"; - var result = MacroTagParser.FormatRichTextContentForPersistence(content); - - Assert.AreEqual( - @" - -

asdfasdf

- -asdfdasf -
-asdfsdf -
- -".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Editor_With_Params_Closing_Tag() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "test2", "value2" } }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

-
- -Macro alias: Map
-

asdfasdf

".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Editor_With_Params_Closing_Tag_And_Content() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "test2", "value2" } }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

-
- -Macro alias: Map
-

asdfasdf

".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Editor_With_Multiline_Parameters() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "test2", "value2\r\ntest" } }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

-
- -Macro alias: Map
-

asdfasdf

".NoCrLf(), - result.NoCrLf()); - } - - [Test] - public void Format_RTE_Data_For_Persistence() - { - var content = @" - -

asdfasdf

-
- -asdfasdf -asdfas -asdfasdfasdf -

asdfasdf

-
-asdfdasf -
-asdfsdf -
- -"; - var result = MacroTagParser.FormatRichTextContentForPersistence(content); - - Assert.AreEqual( - @" - -

asdfasdf

- -asdfdasf -
-asdfsdf -
- -".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Persistence_No_Class() - { - var content = @" - -

asdfasdf

-
- -asdfasdf -asdfas -asdfasdfasdf -

asdfasdf

-
-asdfdasf -
-asdfsdf -
- -"; - var result = MacroTagParser.FormatRichTextContentForPersistence(content); - - Assert.AreEqual( - @" - -

asdfasdf

- -asdfdasf -
-asdfsdf -
- -".StripNewLines(), - result.StripNewLines()); - } - - [Test] - public void Format_RTE_Data_For_Persistence_Custom_Single_Entry() - { - var content = - @"
-
-
-

null

-
-
1089
-
-
"; - var result = MacroTagParser.FormatRichTextContentForPersistence(content); - - Assert.AreEqual( - @"", - result); - } - - [Test] - public void Format_RTE_WhenMacroContainsParameter_EnableInlineMacro_WithValue_1_ItShouldBeInASpan() - { - var content = @"

asdfasdf

-

asdfsadf

- -

asdfasdf

"; - var result = MacroTagParser.FormatRichTextPersistedDataForEditor( - content, - new Dictionary { { "test1", "value1" }, { "enableInlineMacro", "1"} }); - - Assert.AreEqual( - @"

asdfasdf

-

asdfsadf

- - -Macro alias: My.Map.isCool eh[boy!] -

asdfasdf

".StripNewLines(), - result.StripNewLines()); - } -} diff --git a/tests/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroTests.cs b/tests/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroTests.cs deleted file mode 100644 index 0f47546d4b..0000000000 --- a/tests/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Macros/MacroTests.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Umbraco. -// See LICENSE for more details. - -using NUnit.Framework; -using Umbraco.Cms.Core.Cache; -using Umbraco.Cms.Core.Macros; -using Umbraco.Cms.Web.Common.Macros; - -namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Web.Common.Macros; - -[TestFixture] -public class MacroTests -{ - [SetUp] - public void Setup() - { - // We DO want cache enabled for these tests - var cacheHelper = new AppCaches( - new ObjectCacheAppCache(), - NoAppCache.Instance, - new IsolatedCaches(type => new ObjectCacheAppCache())); - } - - [TestCase("anything", true)] - [TestCase("", false)] - public void Macro_Is_File_Based(string macroSource, bool expectedNonNull) - { - var model = new MacroModel { MacroSource = macroSource }; - var filename = MacroRenderer.GetMacroFileName(model); - if (expectedNonNull) - { - Assert.IsNotNull(filename); - } - else - { - Assert.IsNull(filename); - } - } -}